Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 770
Tomáš Kafka Avatar asked Oct 16 '09 22:10

Tomáš Kafka


1 Answers

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

like image 131
itowlson Avatar answered Sep 26 '22 07:09

itowlson