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

夙愿已清 提交于 2019-11-28 23:15:27

问题


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!


回答1:


<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.



来源:https://stackoverflow.com/questions/1580753/wpf-contextmenu-with-itemssource-how-to-bind-to-command-in-each-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!