WPF ListBox Commands within ListBoxItem MVVM Comma

2019-03-03 14:05发布

问题:

I have been trying to find a way to have command buttons within my ListBoxItem's of a ListBox control. I use MVVM and Command Binding to the DataContext via ICommand interface. I am unable to find a way to bind to the Views DataContext from within the ListBox ItemsSource. I continue to get a Command "Not Found" error. Can anyone help me understand how to accomplish this. I believe that it has something to do with the command binding path, but I am unsure. Any help or direction would be great.

回答1:

The DataContext of items in a ListBox will be the item they represent. So if your ItemsSource is bound to a list of Widgets, then the DataContext of your ListBoxItem will be a Widget.

If you need to access the DataContext of the ListBox, rather than the ListBoxItem, then you can use RelativeSource:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}},
                                  Path=DataContext.MyCommand}" />