如何右键单击列表框中的项目并在WPF上打开菜单

我有包含文件的列表框,我希望能够右键单击并打开像删除这样的菜单,以便从列表框中删除文件。

目前我右键单击列表框中的项目后有此function

private void listBoxFiles_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { } 

然后我在右键单击后在XAML删除菜单中实现

       

从我的ListBox中删除文件的function:

 private void MenuItemDelete_Click(object sender, RoutedEventArgs e) { if (listBoxFiles.SelectedIndex == -1) { return; } //string filePath = (listBoxFiles.SelectedItem).ToString(); int index = listBoxFiles.SelectedIndex; listBoxFiles.Items.RemoveAt(index); } 

您已经有一个带有标记的上下文菜单。

如果要执行某些操作,其中一种方法是检查菜单的Clickfunction中单击了哪个项目。 例如,您有下一个列表框:

       ... ... ...  

function可能是下一个:

 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日更新:

这是列表框的另一种变体。 您可以将上下文菜单添加到列表框,但不添加到列表框项目。 例如:

          ... ... ...  

1)当您单击列表框中的空白区域时,此function将取消选择所有项目:

 private void someListBox_MouseDown(object sender, MouseButtonEventArgs e) { someListBox.UnselectAll(); } 

2)单击lisboxt项时,它为蓝色。 当您右键单击列表框项目时,它仍然是蓝色,但如果出现上下文菜单,列表框项目将变为灰色,可能是因为此项目失去焦点。

3)删除function正常:

 private void MenuItemDelete_Click(object sender, RoutedEventArgs e) { if (someListBox.SelectedIndex == -1) { return; } someListBox.Items.RemoveAt(someListBox.SelectedIndex); } 

你写的时候不需要listBoxFiles_PreviewMouseRightButtonDown

        

右键单击后它已经工作了