ListBox.SelectedIndex in ContextMenu event handler

2019-07-08 21:44发布

问题:

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.

回答1:

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



回答2:

Looks like you need to use ListPicker (http://silverlight.codeplex.com/releases/view/75888) with SelectedItems. OR Add some flag of element selection...