Search code examples
c#wpfcanvashittest

Can I HitTest element with lower ZIndex in WPF Canvas?


When I am using System.Windows.Media.VisualTreeHelper.HitTest on mouse clicking canvas, it always returns me the element on top. I mean if there are two elements overlapping each other, the one I get is the one with higher ZIndex in canvas.

I also tried to do it this way, but even after I made IsHitTestVisible = False it still returned this same one to me.

Is there any possibility to get the element "underneath"?


Solution

  • See the section "Hit Testing and Z-Order" here: Hit Testing in the Visual Layer, and a code example here: VisualTreeHelper.HitTest Method.

    In short, you need to use one of the HitTest() methods that take a HitTestResultCallback, and then from your callback return HitTestResultBehavior.Continue until you reach the element you're looking for:

    Point pt = ...
    VisualTreeHelper.HitTest(myCanvas, null,
                             new HitTestResultCallback(MyHitTestResult),
                             new PointHitTestParameters(pt));
    ...
    
    private HitTestResultBehavior MyHitTestResult(HitTestResult result)
    {
        DoSomethingWith(result.VisualHit);
    
        //Set the behavior to return visuals at all z-order levels. 
        return HitTestResultBehavior.Continue;
    }