【发布时间】:2010-12-07 12:50:48
【问题描述】:
我有一组表示菜单项的对象(视图模型)。他们每个人都有一个我想在单击 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