How can I prevent a ListBox from selecting an item when I right-click it?

The tricky part is that each element has a ContextMenu , which I still want to open when it right-clicked (I just don't want to select it).

In fact, if this makes the job easier, I don’t want automatic selection at all, so if there is a way, I can completely disable it, it will be just fine.

I'm thinking of just switching to ItemsControl in fact, as long as I can get virtualization and scrolling to work with it.

+6
c # wpf listbox
source share
1 answer

If you don't want a choice at all, I would definitely go with an ItemsControl, not a ListBox. Virtualization and scrolling can be used with a simple ItemsControl element if they are in the template.

On the other hand, if you need a selection, but just don’t need to right-click, the easiest way is probably to handle the PreviewRightMouseButtonDown event:

 void ListBox_PreviewRightMouseButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } 

The reason for this is that the ListBoxItem is selected when the mouse is clicked, but the context menu is opened with the mouse. Therefore, resolving the mouse down event during the preview phase solves your problem.

However, this does not work if you want the mouse to be processed elsewhere in your ListBox (for example, in a control inside an element). In this case, the easiest way is probably to subclass ListBoxItem to ignore it:

 public class ListBoxItemNoRightClickSelect : ListBoxItem { protected override void OnMouseRightButtonDown(MouseButtonEventArgs e) { } } 

You can explicitly create these ListBoxItems in your ItemsSource or you can also subclass ListBox to automatically use your custom items:

 public class ListBoxNoRightClickSelect : ListBox { protected override DependencyObject GetContainerForItemOverride() { return new ListBoxItemNoRightClickSelect(); } } 

FYI, here are some solutions that won't work along with explanations of why they won't work:

  • You cannot just add a MouseRightButtonDown handler for each ListBoxItem, because the registered class handler will be called before your
  • You cannot handle MouseRightButtonDown in a ListBox because the event is directly dispatched to each control
+16
source share

All Articles