您已经有一个带有标记的上下文菜单。
如果要执行某些操作,其中一种方法是在菜单的单击功能中检查单击了哪个项目。
例如,您有下一个列表框:
<ListBox Name="someListBox">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete" Click="MenuItemDelete_Click"/>
</ContextMenu>
</ListBox.ContextMenu>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
</ListBox>
功能可能是下一个:
private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
{
if (someListBox.SelectedIndex == -1) return;
// Hypothetical function GetElement retrieves some element
var element = GetElement(someListBox.SelectedIndex);
// Hypothetical function DeleteElement
DeleteElement(element);
}
2012 年 3 月 5 日更新:
这是您的列表框的另一种变体。您可以不向列表框添加上下文菜单,而是向列表框项添加上下文菜单。例如:
<ListBox Name="someListBox" MouseDown="someListBox_MouseDown">
<ListBox.Resources>
<!--Defines a context menu-->
<ContextMenu x:Key="MyElementMenu">
<MenuItem Header="Delete" Click="MenuItemDelete_Click"/>
</ContextMenu>
<!--Sets a context menu for each ListBoxItem in the current ListBox-->
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
</Style>
</ListBox.Resources>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
<ListBoxItem>...</ListBoxItem>
</ListBox>
1) 当您点击列表框中的空白区域时,此功能将取消选择所有项目:
private void someListBox_MouseDown(object sender, MouseButtonEventArgs e)
{
someListBox.UnselectAll();
}
2) 当你点击 lisboxt 项目时,它是蓝色的。右键单击列表框项时,它仍然是蓝色的,但如果出现上下文菜单,则列表框项变为灰色,可能是因为该项失去焦点。
3) 删除功能正常:
private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
{
if (someListBox.SelectedIndex == -1)
{
return;
}
someListBox.Items.RemoveAt(someListBox.SelectedIndex);
}