I have a range of controls laid out on a canvas in my application. I am programmatically generating a point on this canvas. I wish to detect if a child of the canvas intersects with this point.
I expected a hit test API to be available (wpf used to have an interface available), but it looks like all interaction seems to be through input and touch events, making it difficult to execute the query myself. It's very possible I've missed this functionality in my searches, does anyone know how to implement such functionality?
You can use Windows.UI.Xaml.Media.VisualTreeHelper.FindElementsInHostCoordinates to find UIElements that intersect a specific coordinate.
To find a point relative to your Canvas you'll need to convert from the Canvas's coordinates to the app window's coordinates, which you can do with UIElement.TransformToVisual. This will take into account scaling as well as translations
// myCanvas is the canvas you're hittesting on
// generatedPoint is the Point you're trying to hittest
// page is the app window's root visual
// Get a transform from the Canvas' coordinates to the Page
GeneralTransform gt = myCanvas.TransformToVisual(page);
// Use that to convert the generated Point into the page's coords
Point pagePoint = gt.TransformPoint(generatedPoint);
// and get the elements in the canvas at that point
var elements = VisualTreeHelper.FindElementsInHostCoordinates(pagePoint,myCanvas);
// elements contains the UIElements at generatedPoint (including myCanvas)
The FindElementsInHostCoordinates docs walk through the hit testing scenario in more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With