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

问题描述 投票:5回答:4

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

有什么好办法吗,谢谢。

例如,一个简单的列表框:项目1 项目2

我想要的行为是当用户点击像素500时(这是在 listbox 但不是项目),当前选中的项目将被取消选择。

c# wpf listbox
4个回答
6
投票

简单的解决方案是将一个属性数据绑定到列表框中。ListBox.SelectedItem 属性,并将其设置为 null 每当你想清除选择的时候,就可以这样做。

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

那么在代码中,你就可以这样做来清除选择。

SelectedItem = null;

那你什么时候会这么做呢?你可以将一个处理程序附加到 PreviewMouseLeftButtonDown 事件Window或你的UI中的任何其他控件。在处理方法中,你可以做一个点击测试,看看用户点击的项目是什么。

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;

当然,方法有很多,你得把我留下的几个空白点填上,但你应该明白了。


EDIT >>&gt。

通用的 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);
    }

    ...
}

0
投票

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

您可以选择以下几种方式

1- 选定后禁用该项目。

2- 保持一个 列表后端 来标记每个索引的可选或不可选。


0
投票

为了保证只有一个项目被选中,将其放在列表框中。

SelectionMode="Single"

然后在点击某个地方时取消选择,你可以尝试检查这个事件。

PreviewMouseLeftButtonUp
LostFocus()

祝贺。


-2
投票

试着确保你的ListBox的背景色是 "透明"。

© www.soinside.com 2019 - 2024. All rights reserved.