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
toListBox
control, not an each item. So, move<toolkit:ContextMenuService.ContextMenu>
block toStackPanel
instead.There are several ways to get element, on which context menu click was performed:
In
Click
handler you havesender
object (it isMenuItem
, I guess)Cast it to
MenuItem
and look toDataContext
of it. It will be item of collection you binded to a list. So, you can find index by:, where
YourListBoxItemCollection
is what you assign toCarsList.ItemsSource
Looks like you need to use ListPicker (http://silverlight.codeplex.com/releases/view/75888) with SelectedItems. OR Add some flag of element selection...