WPF列表框通过单击空白点删除选择

我有一个wpf listbox ,其中包含一个包含矩形的自定义项模板。 可以选择listbox的每个项目(一次只能选择一个)。 我想添加一种行为,当用户点击不是项目的地方时(例如, listbox上的空白点,这不是项目),所选项目将被取消选中。

有任何想法吗? 谢谢。

例如,使用简单的列表框:第1项第2项

我正在寻找的行为是当用户点击像素500(它是listbox的一部分而不是项目的一部分)时,将取消选择当前选择的项目。

简单的解决方案是将属性数据绑定到ListBox.SelectedItem属性,并在每次要清除选择时将其设置为null

  

然后在代码中,您可以这样做以清除选择:

 SelectedItem = null; 

你什么时候做到的? 您可以将处理程序附加到WindowPreviewMouseLeftButtonDown事件或UI中的任何其他控件。 在处理程序方法中,您可以执行命中测试以查看用户单击的项目是:

 HitTestResult hitTestResult = VisualTreeHelper.HitTest(controlClickedOn, e.GetPosition(controlClickedOn)); Control controlUnderMouse = hitTestResult.VisualHit.GetParentOfType(); 

有关此部分的更多帮助,请参见VisualTreeHelper.HitTest Method (Visual, Point)

那么也许是这样的:

 if (controlUnderMouse.GetType() != typeof(ListBoxItem)) SelectedItem = null; 

当然,有很多方法可以做到这一点,你必须填写我留下的几个空白点,但你应该明白这一点。


编辑>>>

通用的GetParentOfType方法是一个自定义的扩展方法 ,它在一个名为DependencyObjectExtensions的单独类中定义:

 public static class DependencyObjectExtensions { public static T GetParentOfType(this DependencyObject element) where T : DependencyObject { Type type = typeof(T); if (element == null) return null; DependencyObject parent = VisualTreeHelper.GetParent(element); if (parent == null && ((FrameworkElement)element).Parent is DependencyObject) parent = ((FrameworkElement)element).Parent; if (parent == null) return null; else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type)) return parent as T; return GetParentOfType(parent); } ... } 

对于The each item in the listbox can be selected (only one at a time).

您可以提出以下其中一项

1-选择后禁用该项目。

2-在后端维护一个列表 ,以标记每个索引可选择或不可选。

要确保只选择一个项目,请将其放入列表框中:

 SelectionMode="Single" 

然后在单击某处时取消选择,您可以尝试检查此事件

 PreviewMouseLeftButtonUp LostFocus() 

问候,

尝试确保ListBox的背景颜色为“透明”