Quantcast
Channel: HitTest confusion
Viewing all articles
Browse latest Browse all 4

HitTest confusion

0
0

I have a button inside a InkCanvas and I'm trying to use VisualTreeHelper to see if the mouse is over it.

At first I did something like this (note, I'm identifying the right element by checking it's data context is set to a particular type of object):

Point p = e.GetPosition(mainCanvas);if (Keyboard.IsKeyDown(Key.LeftCtrl))
{// See if there is a control under the mouseboolselect = false;
  VisualTreeHelper.HitTest(mainCanvas, null, new HitTestResultCallback((htr) =>
  {
    System.Diagnostics.Debug.WriteLine(htr.VisualHit.GetType().Name);
    FrameworkElement elem = htr.VisualHit as FrameworkElement;if (elem != null&& elem.DataContext is myObject)
    {
      selectedElements.Add(elem as UIElement);select = true;return HitTestResultBehavior.Stop;
    }return HitTestResultBehavior.Continue;
  }), new PointHitTestParameters(p));if (select)
  {
    mainCanvas.Select(selectedElements);
  }
}

When I see what is outputted by the debug line I see that it hits InkCanvasSelectionAdorner and TextBlock, but not Button?

So I changed the code to this:

Point p = e.GetPosition(mainCanvas);if (Keyboard.IsKeyDown(Key.LeftCtrl))
{// See if there is a control under the mouseboolselect = false;
  VisualTreeHelper.HitTest(mainCanvas, new HitTestFilterCallback((target) => 
  {
    System.Diagnostics.Debug.WriteLine(target.GetType().Name);
    FrameworkElement elem = target as FrameworkElement;if (elem != null&& elem.DataContext is myObject)
    {
      selectedElements.Add(target as UIElement);select = true;return HitTestFilterBehavior.ContinueSkipChildren;
    }return HitTestFilterBehavior.Continue;
  }), new HitTestResultCallback((htr) =>
  {if (select)
    {return HitTestResultBehavior.Stop;
    }else
    {return HitTestResultBehavior.Continue;
    }
  }), new PointHitTestParameters(p));if (select)
  {
    mainCanvas.Select(selectedElements);
  }
}

Now the filter function sees: InkCanvas, AdornerDecorator, AdornerLayer, InkCanvasSelectionAdorner, InkPresenter, InkCanvasInnerCanvas and, finally, Button.

 

What gives? Why doesn't the HitTest without a filter see all of the objects that should have been hit and, as a result, end up missing the one I want.


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images