我有一个listbox带有自定义项目模板的wpf ,其中包含矩形。listbox可以选择中的每个项目(一次只能选择一个)。我想添加一种行为,当用户单击非项目的地方(例如,不是项目的上的空白点listbox)时,所选项目将被取消选择。
有任何想法吗?谢谢。
例如对于一个简单的列表框:项目1项目2
我要寻找的行为是当用户单击像素500(这是的一部分,listbox而不是某个项目)时,当前选定的项目将被取消选择。
一个简单的解决方案是将一个属性数据绑定到该ListBox.SelectedItem属性,并null在希望清除选择的任何时候将其设置为:
<ListBox ItemsSource="{Binding YourItems}" SelectedItem="{Binding SelectedItem}"
SelectionMode="Single" />
Run Code Online (Sandbox Code Playgroud)
然后在代码中,您只需执行以下操作即可清除选择:
SelectedItem = null;
Run Code Online (Sandbox Code Playgroud)
那你什么时候做?您可以将处理程序的PreviewMouseLeftButtonDown事件的Window,或在您的UI任何其他控制。在处理程序方法中,您可以进行点击测试,以查看用户单击的项目是:
HitTestResult hitTestResult =
VisualTreeHelper.HitTest(controlClickedOn, e.GetPosition(controlClickedOn));
Control controlUnderMouse = hitTestResult.VisualHit.GetParentOfType<Control>();
Run Code Online (Sandbox Code Playgroud)
有关VisualTreeHelper.HitTest Method (Visual, Point)此部分的更多帮助,请参见。
然后也许是这样的:
if (controlUnderMouse.GetType() != typeof(ListBoxItem)) SelectedItem = null;
Run Code Online (Sandbox Code Playgroud)
当然,有很多方法可以做到这一点,您必须填补我留下的几个空白点,但是您应该明白这一点。
编辑>>>
通用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);
}
...
}
Run Code Online (Sandbox Code Playgroud)