C#WPF绑定路径不起作用

时间:2017-11-15 20:58:41

标签: c# wpf xaml data-binding

我目前有一个ListBox,它绑定到一个对象集合,并为集合中的每个对象显示一个按钮。

XAML:

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

    <ListBox x:Name="company_buttons"
             HorizontalContentAlignment="Left" VerticalContentAlignment="Top" 
             Padding="-2,-2,0,0" Height="280" Width="300" Background="{x:Null}" BorderBrush="{x:Null}" Margin="0,0,0,0" BorderThickness="0" 
             ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             ItemsSource="{Binding Buttons_Binding}">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>

                    <Button Background="#FFFCC515" Style="{StaticResource RoundCorner}" FontFamily="Segoe UI" FontSize="16" FontWeight="Bold" TabIndex="0" 
                                CommandParameter="{Binding This_Works}"
                                Command="{Binding HELP WITH THIS}">
                        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="44">
                            <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/>
                            <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/>
                        </StackPanel>
                    </Button>

                    <Label VerticalContentAlignment="Top" Margin="5,0,5,0" Height="19" Padding="0" Foreground="White" FontFamily="Segoe UI" FontSize="12" FontWeight="Bold" Content="{Binding Path}"/>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

以下是绑定中使用的内容:

public class ButtonContent : INotifyPropertyChanged
{
 // stuff
}

public class MainWindowViewModel
{
    public static ObservableCollection<ButtonContent> Buttons_Binding
    {
 // stuff
    }

    public ICommand Command
    {
 // stuff
    }

我的问题是我不知道如何将按钮单击绑定到Command,因为它位于集合Buttons_Binding之外,因此不在同一数据上下文中。我从示例中看到的所有内容以及我尝试过的内容都失败了。

1 个答案:

答案 0 :(得分:1)

由于每个Button都绑定到ListBoxItem的DataContext,因此它无法访问ListBox的DataContext。但是,您可以使用绑定中的RelativeSource遍历可视树。试试这个

{{1}}