解决方法
关键是将PreviewMouseRightButtonDown事件设置在正确的位置.你会注意到,即使没有ContextMenu右键单击一个ListViewItem将选择该项目,因此我们需要在每个项目上设置事件,而不是在ListView上.
<ListView> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}"> <EventSetter Event="PreviewMouseRightButtonDown" Handler="OnListViewItemPreviewMouseRightButtonDown" /> </Style> </ListView.ItemContainerStyle> <ListView.ContextMenu> <ContextMenu> <MenuItem Header="Menu Item">Item 1</MenuItem> <MenuItem Header="Menu Item">Item 2</MenuItem> </ContextMenu> </ListView.ContextMenu> <ListViewItem>Item</ListViewItem> <ListViewItem>Item</ListViewItem> <ListViewItem>Item</ListViewItem> <ListViewItem>Item</ListViewItem> <ListViewItem>Item</ListViewItem> <ListViewItem>Item</ListViewItem> </ListView>
private void OnListViewItemPreviewMouseRightButtonDown(object sender,MouseButtonEventArgs e) { Trace.WriteLine("Preview MouseRightButtonDown"); e.Handled = true; }
由于预览事件为tunneling,因此将阻止RightMouseButtonDown发生在ListViewItems上,从而阻止它们被选中,但不会阻止ListView上的RightMouseButtonDown,因此仍允许ContextMenu打开.