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

Tomáš Kafka picture Tomáš Kafka · Oct 17, 2009 · Viewed 34.2k times · Source

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!

Answer

itowlson picture itowlson · Oct 17, 2009
<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.