WPF ContextMenu对象与ItemsSource的 - 如何绑定到命令中的每个项目? [英] WPF ContextMenu with ItemsSource - how to bind to Command in each item?

查看:2174
本文介绍了WPF ContextMenu对象与ItemsSource的 - 如何绑定到命令中的每个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/898852/specify-command-for-menuitem-in-a-datatemplate\">Specify命令菜单项中的一个DataTemplate


我有那再present菜单项的对象(的ViewModels)的集合。他们每个人都有,我想在单击菜单项时执行的命令。

如果我想要做静态菜单,我这样做是这样的:

 &LT;&文本菜单GT;
    &LT;菜单项标题={结合文本1}命令= {结合COMMAND1}&GT;
    &LT;菜单项标题={结合文本2}命令= {绑定命令2}&GT;
&LT; /文本菜单&GT;

但我不知道事先的项目(他们来自一个集合),我需要分配ContextMenu.ItemsSource - 并把文成的ItemTemplate

 &LT;文本菜单的ItemsSource ={结合MyMenuItems}&GT;
    &LT; ContextMenu.ItemTemplate&GT;
        &LT;&DataTemplate的GT;
            &LT; TextBlock的文本={结合文本2}/&GT; &LT;! - 但是,在把命令绑定? TextBlock.Command是没有意义的,我们必须菜单项进不去! - &GT;
        &LT; / DataTemplate中&GT;
    &LT; /ContextMenu.ItemTemplate>
&LT; /文本菜单&GT;

这样的话,但是,我没有地方绑定的命令 - !因为我无法获得菜单项的每一行

任何意见,请?谢谢你,伙计们!


解决方案

 &LT; ContextMenu.ItemContainerStyle&GT;
  &LT;风格的TargetType =菜单项&GT;
    &LT; setter属性=命令VALUE ={结合AssociatedCommand}/&GT;
  &LT; /样式和GT;
&LT; /ContextMenu.ItemContainerStyle>

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

Possible Duplicate:
Specify Command for MenuItem in a DataTemplate

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>

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>

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>

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

这篇关于WPF ContextMenu对象与ItemsSource的 - 如何绑定到命令中的每个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆