简体   繁体   中英

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

I'm wondering how I would go about this. I can't very well check that mouse is not over item1, item2, ...., can I? there should be some better way of doing this. I just want to deselect all the items if the user clicks on non-item space.

You can do what you want... in your Click handler, add this code:

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

The GetParentOfType method is an extension method that I created and is as follows:

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

Please note that extension methods need to be placed into a static class... you could always refactor it into a normal method if you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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