带有 ItemsSource 的 WPF ContextMenu - 如何在每个项目中绑定到 Command? [英] WPF ContextMenu with ItemsSource - how to bind to Command in each item?
问题描述
可能重复:
在 DataTemplate 中为 MenuItem 指定命令
我有一组代表菜单项的对象(视图模型).他们每个人都有一个我想在单击 MenuItem 时执行的命令.
I have a collection of objects (viewmodels) that represent menu items. Each of them have a command that I would like to execute when a MenuItem is clicked.
如果我想静态地做菜单,我会这样做:
If I wanted to do the menu statically, I do it like this:
<ContextMenu>
<MenuItem Header="{Binding Text1}" Command={Binding Command1}>
<MenuItem Header="{Binding Text2}" Command={Binding Command2}>
</ContextMenu>
但是当我事先不知道项目(它们来自集合)时,我需要分配 ContextMenu.ItemsSource - 并将文本放入 ItemTemplate.
but when I don't know the items in advance (they come from a collection), I need to assign ContextMenu.ItemsSource - and put a text into a ItemTemplate.
<ContextMenu ItemsSource="{Binding MyMenuItems}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text2}" /> <!-- But where to put Command binding? TextBlock.Command makes no sense, and we have no access to MenuItem! -->
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
但是,这样一来,我就无法将 Command 绑定到 - 因为我无法为每一行获取 MenuItem!
This way, however, I have no place to bind a Command to - because I can't get the MenuItem for every row!
有什么建议吗?谢谢各位!
Any advice, please? Thank you, guys!
推荐答案
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding AssociatedCommand}" />
</Style>
</ContextMenu.ItemContainerStyle>
其中 AssociatedCommand 是 viewmodel 对象上包含 ICommand 的属性.
where AssociatedCommand is the property on the viewmodel object that holds the ICommand.
这篇关于带有 ItemsSource 的 WPF ContextMenu - 如何在每个项目中绑定到 Command?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!