Default WPF HitTest behaviour with Hidden/Collapsed elements
Asked Answered
P

1

8

in WPF when using VisualTreeHelper.HitTest even hidden Elements are found. To skip this elements and only return a result for visible ones, i created a HitTestFilter like the following :

///This Filter should cut all invisible or not HitTest Enabled Elements
private static HitTestFilterBehavior MyHitTestFilter(DependencyObject target)
{
    var uiElement = target as UIElement;
    if (uiElement != null){
        if(!uiElement.IsHitTestVisible || !uiElement.IsVisible))
            return HitTestFilterBehavior.ContinueSkipSelfAndChildren;
    }
    return HitTestFilterBehavior.Continue;
}

This Filter does his job, but i like to know what the default WPF HitTesting does in this case? Does it use a similar filter? Are there any other, maybe better options for doing this?

To clarify a short description :

Layout example

In the image there is

  1. A Layout Container as the root element
  2. Button1 which is visible
  3. Above Button1 is Button2 which is invisible

If i got such a layout and do a mouseclick in the green area of Button2, WPF skips Button2 and the click event appears on Button1.

If i do manual HitTesting without the filter described earlier, i will get Button2 as the result.

So the question is, what is the default behaviour/filter WPF is using?

Thanks in advance for any suggestions.

Paske answered 2/7, 2014 at 11:59 Comment(4)
Can't reproduce this for Collapsed elements. And that would be strange anyway as they would not have been laid out.Lyn
oh you are right. i will edit my question, i thought i tested it with collapsed. sorry.Paske
There is a lot to explain about this. You might however get a .Net decompiler (like the free JetBrains dotPeek) and take a look at the implementation of e.g. the UIElement.InputHitTest method.Lyn
Possible duplicate of WPF UIElement.IsHitTestVisible=false; still returning hits?Quotidian
T
10

I know this is rather old question, but I had similar issue recently and got it working by using UIElement.InputHitTest method.

I replaced

HitTestResult hitTest = VisualTreeHelper.HitTest(rootVisual, point);
IInputElement source = hitTest?.VisualHit as IInputElement;

With

IInputElement source = rootVisual.InputHitTest(point);

The second version skips invisible elements (while the first doesn't).

Teador answered 15/2, 2017 at 10:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.