Problem with VisualTreeHelper.HitTest in WPF

后端 未结 2 507
闹比i
闹比i 2020-12-11 20:29

I\'m trying to hit-test a bunch of UserControls on a Canvas. I don\'t want the HitTest() to walk the whole way through the visual tree, so I\'m using the FilterCallback to

2条回答
  •  猫巷女王i
    2020-12-11 20:49

    I had this same problem of HitTest not finding a user control. Apparently this is by design (http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/005dad03-c8eb-405f-9567-50653a0e612c).

    I worked around this by handling the hit of some element inside the user control, and then finding the parent user control using the VisualTreeHelper.GetParent method. I'm not very familiar with WPF yet, so I'm not sure if it would be better to use FrameworkElement.Parent property.

    However, here is my method for finding the user control (or any visual parent of some required type) after first finding some of its content elements by hit test:

    public static T GetVisualParent(this DependencyObject element) where T : DependencyObject
    {
        while (element != null && !(element is T))
            element = VisualTreeHelper.GetParent(element);
    
        return (T)element;
    }
    

提交回复
热议问题