How can I detect the control under a point in uwp

久未见 提交于 2019-12-07 20:26:52

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38625268/how-can-i-detect-the-control-under-a-point-in-uwp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!