如何在uwp中的某个点下检测控件

Jos*_*shG 2 c# uwp

我的应用程序中的画布上放置了一系列控件.我在这个画布上以编程方式生成一个点.我希望检测画布的孩子是否与此点相交.

我期望一个命中测试API可用(wpf曾经有一个接口可用),但看起来所有的交互似乎都是通过输入和触摸事件,这使得我自己很难执行查询.我很可能在搜索中错过了这个功能,有谁知道如何实现这样的功能?

Rob*_*SFT 6

您可以使用Windows.UI.Xaml.Media.VisualTreeHelper.FindElementsInHostCoordinates查找与特定坐标相交的UIElements.

要找到相对于Canvas的点,您需要将Canvas的坐标转换为应用程序窗口的坐标,您可以使用UIElement进行转换.TransformToVisual.这将考虑缩放和翻译

// 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)
Run Code Online (Sandbox Code Playgroud)

FindElementsInHostCoordinates文档更详细地穿行命中测试场景.