WPF ListBox Commands within ListBoxItem MVVM Command Binding

4.1k views Asked by At

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

There are 1 answers

2
GazTheDestroyer On BEST ANSWER

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}" />