带有 ItemsSource 的 WPF ContextMenu - 如何绑定到每个项目中的 Command?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1580753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:06:35  来源:igfitidea点击:

WPF ContextMenu with ItemsSource - how to bind to Command in each item?

wpfbindingcommandcontextmenu

提问by Tomá? Kafka

Possible Duplicate:
Specify Command for MenuItem in a DataTemplate

可能的重复:
为 DataTemplate 中的 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.

我有一组代表菜单项的对象(视图模型)。他们每个人都有一个我想在单击 MenuItem 时执行的命令。

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>

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 - 并将文本放入 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>

This way, however, I have no place to bind a Command to - because I can't get the MenuItem for every row!

但是,通过这种方式,我没有地方可以将 Command 绑定到 - 因为我无法获取每一行的 MenuItem!

Any advice, please? Thank you, guys!

请问有什么建议吗?谢谢你们!

回答by itowlson

<ContextMenu.ItemContainerStyle>
  <Style TargetType="MenuItem">
    <Setter Property="Command" Value="{Binding AssociatedCommand}" />
  </Style>
</ContextMenu.ItemContainerStyle>

where AssociatedCommand is the property on the viewmodel object that holds the ICommand.

其中 AssociatedCommand 是保存 ICommand 的视图模型对象上的属性。