简单的解决方案是将一个属性与
ListBox.SelectedItem
属性进行数据绑定,并在需要清除选择时将其设置为
null
:
<ListBox ItemsSource="{Binding YourItems}" SelectedItem="{Binding SelectedItem}"
SelectionMode="Single" />
然后在代码中,你只需执行以下操作即可清除选择内容:
SelectedItem = null;
你什么时候会这样做呢?你可以将一个处理程序附加到Window
或UI中的任何其他控件的PreviewMouseLeftButtonDown
事件。在处理程序方法中,您可以进行命中测试以查看用户单击的项是什么:
HitTestResult hitTestResult =
VisualTreeHelper.HitTest(controlClickedOn, e.GetPosition(controlClickedOn));
Control controlUnderMouse = hitTestResult.VisualHit.GetParentOfType<Control>();
查看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);
}
...
}