问题描述
我一直在尝试在 ListBox 控件的 ListBoxItem的中使用命令按钮的方法.我使用 MVVM和通过ICommand接口将命令绑定到DataContext .我找不到从ListBox ItemsSource 中的绑定到Views DataContext的方法.我继续收到命令未找到" 错误.谁能帮助我了解如何实现这一目标.我相信这与命令绑定路径有关,但是我不确定.任何帮助或指示都将很好.
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.
推荐答案
ListBox
中项目的DataContext
将是它们表示的项目.因此,如果ItemsSource
绑定到小部件列表,则ListBoxItem
的DataContext
将是小部件.
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.
如果需要访问ListBox
的DataContext
,而不是ListBoxItem
,则可以使用RelativeSource
:
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}" />
这篇关于ListBoxItem MVVM命令绑定中的WPF ListBox命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!