ContextMenu事件处理程序中的ListBox.SelectedIndex [英] ListBox.SelectedIndex in ContextMenu event handler
问题描述
我有一个带有上下文菜单的列表框.如何在ContextMenuItem单击事件处理程序中获取SelectedIndex(SelectedItem)属性的值?当前在事件Edit_Click和Delete_CLick中,CarsList.SelectedIndex的值始终为-1.
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.
在XAML中,这是我的列表框:
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>
谢谢.
推荐答案
首先,您已将Context Menu
分配给ListBox
控件,而不是每个项目.因此,将<toolkit:ContextMenuService.ContextMenu>
块移至StackPanel
.
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:
在Click
处理程序中,您具有sender
对象(我想是MenuItem
)
In Click
handler you have sender
object (it is MenuItem
, I guess)
将其投射到MenuItem
并查看它的DataContext
.这将是您绑定到列表的集合项.因此,您可以通过以下方式找到索引:
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)
,其中YourListBoxItemCollection
是您分配给CarsList.ItemsSource
这篇关于ContextMenu事件处理程序中的ListBox.SelectedIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!