繁体   English   中英

WPF树视图如何在树视图中而不是在树视图上处理鼠标单击?

[英]WPF treeview how to handle mouse clicks in treeview but not on a treeviewitem?

我想知道我该怎么做。 我不能很好地检查鼠标是否不在item1,item2,...上,可以吗? 应该有一些更好的方法来做到这一点。 如果用户单击非项目空间,我只想取消选择所有项目。

您可以在Click处理程序中执行所需的操作,添加以下代码:

HitTestResult hitTestResult = VisualTreeHelper.HitTest(uiElement, DragStartPosition);
TreeViewItem listBoxItem = hitTestResult.VisualHit.GetParentOfType<TreeViewItem>();
if (listBoxItem == null) 
{
    // user has clicked, but not on a TreeViewItem
}

GetParentOfType方法是我创建的扩展方法,如下所示:

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);
}

请注意, 扩展方法需要放置在static类中……如果愿意,您始终可以将其重构为普通方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM