7

I would like to perform a rectangual hit test on WPF Canvas component in order to get Controls that are overlapped by a Rectangle framework element. I found a Silverlight's VisualTreeHelper.FindElementsInHostCoordinates method, but apparently it's not available in WPF.

What's the best method to achieve such functionality?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Darius
  • 524
  • 1
  • 5
  • 11

2 Answers2

3

Supposing you have a call like this in Silverlight

var result = VisualTreeHelper.FindElementsInHostCoordinates(myPoint, myUIElement);

then this WPF code should have an equivalent result

var result = new List<DependencyObject>(); 
                         //changed from external edits, because VisualHit is
                         //only a DependencyObject and may not be a UIElement
                         //this could cause exceptions or may not be compiling at all
                         //simply filter the result for class UIElement and
                         //cast it to IEnumerable<UIElement> if you need
                         //the very exact same result including type

VisualTreeHelper.HitTest(
    myUiElement,
    null,
    new HitTestResultCallback(
        (HitTestResult hit)=>{
            result.Add(hit.VisualHit);
            return HitTestResultBehavior.Continue;
        }),
    new PointHitTestParameters(myPoint));

in your special case you might want to use GeometryHitTestParameters instead of PointHitTestParameters to do a Rect-Test.

thewhiteambit
  • 1,365
  • 16
  • 31
3

The closest equivalent is VisualTreeHelper.HitTest. It works significantly differently to Silverlight's FindElementsInHostCoordinates, but you should be able to use it for your needs.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
KeithMahoney
  • 3,323
  • 19
  • 10