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

时间:2014-04-17 12:46:41

标签: c# wpf listbox

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

有什么想法吗? 感谢。

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

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

4 个答案:

答案 0 :(得分:4)

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

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

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

SelectedItem = null;

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

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

有关此部分的更多帮助,请参阅PreviewMouseLeftButtonDown event

然后可能是这样的:

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

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


编辑&gt;&gt;&gt;

通用GetParentOfType方法是自定义VisualTreeHelper.HitTest Method (Visual, Point),它在名为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);
    }

    ...
}

答案 1 :(得分:0)

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

您可以提出以下其中一项

1-选择项目后禁用该项目。

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

答案 2 :(得分:0)

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

SelectionMode="Single"

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

PreviewMouseLeftButtonUp
LostFocus()

此致

答案 3 :(得分:-2)

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