【问题标题】:WPF ContextMenu with ItemsSource - how to bind to Command in each item? [duplicate]带有 ItemsSource 的 WPF ContextMenu - 如何在每个项目中绑定到 Command? [复制]
【发布时间】:2010-12-07 12:50:48
【问题描述】:

可能重复:
Specify Command for MenuItem in a DataTemplate

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

如果我想静态地做菜单,我会这样做:

<ContextMenu>
    <MenuItem Header="{Binding Text1}" Command={Binding Command1}>
    <MenuItem Header="{Binding Text2}" Command={Binding Command2}>
</ContextMenu>

但是当我事先不知道项目(它们来自集合)时,我需要分配 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>

但是,这样一来,我就无法将 Command 绑定到 - 因为我无法为每一行获取 MenuItem!

有什么建议吗?谢谢各位!

【问题讨论】:

标签: wpf binding command contextmenu


【解决方案1】:
<ContextMenu.ItemContainerStyle>
  <Style TargetType="MenuItem">
    <Setter Property="Command" Value="{Binding AssociatedCommand}" />
  </Style>
</ContextMenu.ItemContainerStyle>

其中 AssociatedCommand 是 viewmodel 对象上包含 ICommand 的属性。

【讨论】:

  • 谢谢,我已经在链接线程中找到了相同的答案...
  • 如何分隔两个菜单项的命令。
  • 如何分隔多个菜单项的命令?比如说“添加”和“删除”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2011-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多