HaloMediaz
HaloMediaz

Reputation: 1263

Get name(or index) of selected menu item from context menu, which was dynamically generated via ItemsSource bound to a ObservableCollection

I have a context menu that contains 1 menu item. That menu item is bound to a ObservableCollection for the itemssource.

         <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Example Menu Item" 
                          Command="{Binding Path=DataContext.ExampleCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}"
                          ItemsSource="{Binding ObservableItems}">
                </MenuItem>
            </ContextMenu>
        </ListView.ContextMenu>

How do I get the name (or index) of the menu item that was selected. The problem is I cannot bind a command to each individual menu item, as they are dynamically generated.

For example how would I know which item was clicked, as seen in the image below?

enter image description here

Any help is much appreciated. Thanks.

Upvotes: 0

Views: 1972

Answers (1)

dkozl
dkozl

Reputation: 33364

You still can bind Command and CommandParameter per item for dynamically generated lists but you need to use ItemContainerStyle

<ContextMenu>
    <MenuItem Header="Example Menu Item" ItemsSource="{Binding ObservableItems}">
        <MenuItem.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Command" Value="{Binding Path=DataContext.ExampleCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}"/>
                <Setter Property="CommandParameter" Value="{Binding}"/>
            </Style>
        </MenuItem.ItemContainerStyle>
    </MenuItem>
</ContextMenu>

in this example CommandParameter, which is passed to you ExampleCommand command as parameter, will be an item in your collection (current DataContext of child item)

EDIT

To get index you can use pair of ItemsControl properties: AlternationCount and AlternationIndex. You set AlternationCount to number of items in your collection and pass AlternationIndex to your command

<MenuItem Header="Example Menu Item" ItemsSource="{Binding ObservableItems}" AlternationCount="{Binding ObservableItems.Count}">
   <MenuItem.ItemContainerStyle>
      <Style TargetType="{x:Type MenuItem}">
         <Setter Property="Command" Value="{Binding ...}"/>
         <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self}, Path=(ItemsControl.AlternationIndex)}"/>
      </Style>
   </MenuItem.ItemContainerStyle>
</MenuItem>

Upvotes: 3

Related Questions