[英]How can I prevent ListBox from selecting an item when I right-click it?
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).棘手的部分是每个项目都有一个
ContextMenu
,当它被右键单击时我仍然想打开它(我只是不希望它选择它)。
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.我正在考虑实际上只是切换到
ItemsControl
,只要我可以获得虚拟化和滚动来使用它。
If you don't want selection at all I would definitely go with ItemsControl not ListBox.如果您根本不需要选择,我肯定会选择 ItemsControl 而不是 ListBox。 Virtualization and scrolling both can be used with a plain ItemsControl as long as they are in the template.
虚拟化和滚动都可以与普通的 ItemsControl 一起使用,只要它们在模板中即可。
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:另一方面,如果您需要选择但不想右键单击选择,最简单的方法可能是处理 PreviewRightMouseButtonDown 事件:
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 .这样做的原因是 ListBoxItem 选择发生在鼠标按下时,但上下文菜单打开发生在鼠标抬起时。 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).但是,如果您希望在 ListBox 中的其他地方(例如在项目中的控件中)处理鼠标按下,则这不起作用。 In this case the easiest way is probably to subclass ListBoxItem to ignore it:
在这种情况下,最简单的方法可能是将 ListBoxItem 子类化以忽略它:
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:您可以在 ItemsSource 中显式构建这些 ListBoxItems,也可以子类化 ListBox 以自动使用您的自定义项:
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:仅供参考,以下是一些不起作用的解决方案以及为什么它们不起作用的解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.