WPF列表框单击空白处选择删除 [英] WPF Listbox remove selection by clicking on a blank spot

查看:564
本文介绍了WPF列表框单击空白处选择删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF 列表框与其中包含一个矩形的自定义项模板。
中的在列表框的每个项目可以选择(仅一次)。
我想补充,当用户点击一个地方,其中一个行为,是不是该项目(例如,在列表框的空白处,其中是不是一个项目),所选项目将成为取消。

I have a wpf listbox with a custom item template which contains a rectangle. The each item in the listbox can be selected (only one at a time). I want to add a behavior in which when a user clicks on a place which isn't the item (for instance, a blank spot on the listbox, which is not an item), the selected item will become deselected.

任何想法?
谢谢

Any ideas? Thanks.

例如用一个简单的列表框:


项目1
项目2

For example with a simple listbox: item 1 item 2

这是我在寻找的行为是当像素500(这是一部分的用户点击列表框而不是一个项目),当前选择的项目将被取消。

The behavior that I'm looking for is when the user clicks on pixel 500 (which is a part of the listbox but not on an item), the currently selected item will be deselected.

推荐答案

简单的解决方案是将数据绑定属性到 ListBox.SelectedItem 属性并将其设置为每当你想清除的选择:

The simple solution is to data bind a property to the ListBox.SelectedItem property and set it to null whenever you want to clear the selection:

<ListBox ItemsSource="{Binding YourItems}" SelectedItem="{Binding SelectedItem}" 
    SelectionMode="Single" />



然后在代码中,你可以这样做是为了清除选择:

Then in code, you can just do this to clear the selection:

SelectedItem = null;

和时你会怎么做呢?您可以将处理程序附加到的窗口中> 的PreviewMouseLeftButtonDown 事件,或在你的UI任何其它控制。在该处理方法,你可以做的命中测试,看看用户点击的项目是:

And when would you do that? You can attach a handler to the PreviewMouseLeftButtonDown event of the Window, or any other control in your UI. In the handler method, you could do a hit test to see what the item the user clicked on was:

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



见的 VisualTreeHelper.HitTest方法(视觉,点) 获得更多的帮助这部分

See the VisualTreeHelper.HitTest Method (Visual, Point) for more help with this part.

那么,也许是这样的:

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



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

Of course, there are many ways to do this, and you'll have to fill in the few blank spots that I left, but you should get the idea.

这篇关于WPF列表框单击空白处选择删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆