WPF在特定坐标处获取元素

4 c# wpf coordinate-systems

我在画布中有标签,我需要获取与坐标X,Y相交的标签吗?

谢谢!!

Jul*_*ain 6

只需InputHitTest在画布上使用,将所需的坐标作为参数即可传递。请注意,该InputHitTest功能适用于所有UIElement画布,并非特定于画布。

  • 您可以使用WPF中的HitTesting遍历多个项目,即使它们重叠。您可以将VisualTreeHelper.HitTest与回调一起使用。例如,查看此SO答案的命中测试代码:http://stackoverflow.com/questions/6410146/dockable-windows-floating-window-and-mainwindow-menu-integration/6770950#6770950 (4认同)

Ed *_*tes 3

Canvas.GetLeft(element)、Canvas.GetTop(element) 将获取任何元素的位置。使用 ActualWidth 和 ActualHeight 形成完整的矩形。您可以使用 foreach 遍历画布的子元素。

编辑: CodeNaked 指出元素可以使用 SetRight 或 SetBottom 设置,因此我修改了示例代码:

foreach (FrameworkElement nextElement in myCanvas.Children)
{
    double left = Canvas.GetLeft(nextElement);
    double top = Canvas.GetTop(nextElement);
    double right = Canvas.GetRight(nextElement);
    double bottom = Canvas.GetBottom(nextElement);
    if (double.IsNaN(left))
    {
        if (double.IsNaN(right) == false)
            left = right - nextElement.ActualWidth;
        else
            continue;
    }
    if (double.IsNaN(top))
    {
        if (double.IsNaN(bottom) == false)
            top = bottom - nextElement.ActualHeight;
        else
            continue;
    }
    Rect eleRect = new Rect(left, top, nextElement.ActualWidth, nextElement.ActualHeight);
    if (myXY.X >= eleRect.X && myXY.Y >= eleRect.Y && myXY.X <= eleRect.Right && myXY.Y <= eleRect.Bottom)
    {
        // Add to intersects list
    }
}
Run Code Online (Sandbox Code Playgroud)