简单的解决方案是将属性数据绑定到ListBox.SelectedItem
属性并将其设置为null
每当你想清除选择时:
<ListBox ItemsSource="{Binding YourItems}" SelectedItem="{Binding SelectedItem}"
SelectionMode="Single" />
然后在代码中,您可以执行以下操作来清除选择:
SelectedItem = null;
你什么时候会这样做?您可以将处理程序附加到PreviewMouseLeftButtonDown event of the Window
,或 UI 中的任何其他控件。在处理程序方法中,您可以进行命中测试以查看用户单击的项目是什么:
HitTestResult hitTestResult =
VisualTreeHelper.HitTest(controlClickedOn, e.GetPosition(controlClickedOn));
Control controlUnderMouse = hitTestResult.VisualHit.GetParentOfType<Control>();
See the VisualTreeHelper.HitTest Method (Visual, Point)以获得有关这部分的更多帮助。
那么也许是这样的:
if (controlUnderMouse.GetType() != typeof(ListBoxItem)) SelectedItem = null;
当然,有很多方法可以做到这一点,您必须填写我留下的几个空白,但您应该明白这个想法。
编辑>>>
通用的GetParentOfType
方法是自定义的扩展方法它是在一个名为的单独的类中定义的DependencyObjectExtensions
:
public static class DependencyObjectExtensions
{
public static T GetParentOfType<T>(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<T>(parent);
}
...
}