I have a listbox with context menu. How can I get value of SelectedIndex (SelectedItem) property in ContextMenuItem click event handler? Currently in events Edit_Click and Delete_CLick a value of CarsList.SelectedIndex always is -1.
Here my ListBox in XAML:
<ListBox Name="CarsList" Style="{StaticResource ListBoxStyle}" Margin="26,0,26,0" Height="380" > <toolkit:ContextMenuService.ContextMenu> <toolkit:ContextMenu Name="ContextMenu" > <toolkit:MenuItem Name="Edit" Header="Edit" Click="Edit_Click"/> <toolkit:MenuItem Name="Delete" Header="Delete" Click="Delete_Click"/> </toolkit:ContextMenu> </toolkit:ContextMenuService.ContextMenu> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding CarName}" TextTrimming="WordEllipsis" Foreground="Black" FontSize="24" Width="428"/> <TextBlock Text="{Binding VIN}" TextWrapping="Wrap" Foreground="Gray" FontSize="20" Width="428"/> <TextBlock Text="{Binding Date}" TextWrapping="Wrap" Foreground="Gray" FontSize="20" Width="428"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Thanks.
First of all you have assigned Context Menu to ListBox control, not an each item. So, move <toolkit:ContextMenuService.ContextMenu> block to StackPanel instead.
There are several ways to get element, on which context menu click was performed:
In Click handler you have sender object (it is MenuItem, I guess)
Cast it to MenuItem and look to DataContext of it. It will be item of collection you binded to a list. So, you can find index by:
int selectedIndex = YourListBoxItemCollection.IndexOf((sender as MenuItem).DataContext)
, where YourListBoxItemCollection is what you assign to CarsList.ItemsSource
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With