Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

wpf

listbox

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

In fact, if it makes things any easier, I don't want any automatic selection at all, so if there's some way I can disable it entirely that would be just fine.

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

like image 547
devios1 Avatar asked Jun 09 '10 23:06

devios1


1 Answers

If you don't want selection at all I would definitely go with ItemsControl not ListBox. Virtualization and scrolling both can be used with a plain ItemsControl as long as they are in the template.

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

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

The reason this works is that ListBoxItem selection happens on mouse down but context menu opening happens on mouse up. So eliminating the mouse down event during the preview phase solves your problem.

However this does not work if you want mouse down to be handled elsewhere within your ListBox (such as in a control within an item). 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 either explicitly construct these ListBoxItems in your ItemsSource or you can also subclass ListBox to use your custom items automatically:

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

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

  • You can't just add a MouseRightButtonDown handler on each ListBoxItem because the registered class handler will get called before yours
  • You can't handle MouseRightButtonDown on ListBox because the event is directly routed to each control individually
like image 123
Ray Burns Avatar answered Oct 21 '22 01:10

Ray Burns