WPF ContextMenu with ItemsSource - how to bind to Command in each item?
<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.
Tomáš Kafka
Tomaskafka.com, author of Weathergraph watchface for Garmin & Pebble. linkedin.com/tomaskafka
Updated on October 17, 2020Comments
-
Tomáš Kafka over 3 years
Possible Duplicate:
Specify Command for MenuItem in a DataTemplateI 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!