在 Xamarin 中获取元素相对于屏幕的位置

Kar*_*hik 5 c# position xamarin xamarin.forms

我有一个带有上下文菜单的列表,当我单击时,选项列表(编辑、删除、信息)将显示在弹出窗口中。

在这里,我需要在上下文菜单图标的左下方显示此弹出窗口,因为我需要上下文菜单相对于屏幕的位置。

谁能帮我获取 Xamarin 中元素的 XY 位置?

提前致谢!

Dav*_*rke 6

这是我在Xamarin 论坛中找到的方法的版本:

public static class ScreenCoords
{
    /// <summary>
    /// A view's default X- and Y-coordinates are LOCAL with respect to the boundaries of its parent,
    /// and NOT with respect to the screen. This method calculates the SCREEN coordinates of a view.
    /// The coordinates returned refer to the top left corner of the view.
    /// </summary>
    public static Point GetScreenCoords(this VisualElement view)
    {
        var result = new Point(view.X, view.Y);
        while (view.Parent is VisualElement parent)
        {
            result = result.Offset(parent.X, parent.Y);
            view = parent;
        }
        return result;
    }
Run Code Online (Sandbox Code Playgroud)