ListBox.SelectedIndex in ContextMenu event handler

浪子不回头ぞ 提交于 2019-12-11 03:14:38

问题


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...



来源:https://stackoverflow.com/questions/9259116/listbox-selectedindex-in-contextmenu-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!