带有 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 是保存 ICommand 的视图模型对象上的属性.
where AssociatedCommand is the property on the viewmodel object that holds the ICommand.
这篇关于带有 ItemsSource 的 WPF ContextMenu - 如何绑定到每个项目中的 Command?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!