WPF ListBox Commands within ListBoxItem MVVM Command Binding

拜拜、爱过 提交于 2019-12-02 16:13:04

问题


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


来源:https://stackoverflow.com/questions/31007687/wpf-listbox-commands-within-listboxitem-mvvm-command-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!