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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With