WPF弹出控件 - 查找X,Y坐标

6
我正在尝试获取弹出控件的X,Y坐标。我已经尝试过:
VisualTreeHelper.GetOffset(Popup);
但是返回的向量始终包含X和Y的值为0。
弹出窗口的父级是布局根,即网格。
CustomPopupPlacementCallback的Point参数始终返回0,0。
目标是允许用户将弹出窗口拖动到屏幕上的任何位置。我想通过获取当前弹出窗口和鼠标位置,并朝着鼠标移动的方向移动弹出窗口来实现这一目标。
--------------------更新--------------------
Chris Nicol,我已经尝试了您的答案,并使用以下代码,但仍然收到rootPoint的0,0:
Xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Test.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="800" Height="600">    

<Grid x:Name="LayoutRoot">
    <Popup x:Name="Popup" IsOpen="True" Placement="Center" Width="100" Height="100">
        <Button Click="Button_Click" Content="Test" />
    </Popup>
</Grid>

代码后台:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();

        // Insert code required on object creation below this point.
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        GeneralTransform transform = Popup.TransformToAncestor(LayoutRoot);
        Point rootPoint = transform.Transform(new Point(0, 0));
    }
}

我没有找到解决方案。对长时间的延迟感到抱歉。 - gamzu07
2个回答

2

我不确定这是发现问题的最佳方法,但它确实有效:

GeneralTransform transform = controlToFind.TransformToAncestor(TopLevelControl);
            Point rootPoint = transform.Transform(new Point(0, 0));

是的,那确实是最好的方法。我通常会在单行代码中完成:controlToFind.TransformToAncestor(TopLevelControl).Transform(new Point(0,0)) - Ray Burns
是的,同样,我用一行代码完成。我只是为了示例而将其分开,以便更容易理解。 - Chris Nicol
感谢迄今为止的帮助,如果您有时间,请查看我的更新。 - gamzu07
2
我尝试在ContextMenu.OnMenuOpened事件处理程序中使用TransformToAncestor方法,但是我收到了一个异常:“指定的Visual不是此Visual的祖先。” - Rudolf Dvoracek

1

你必须使用win32 api:

将以下内容添加到你的类中:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int Left; // X coordinate of topleft point
        public int Top; // Y coordinate of topleft point
        public int Right; // X coordinate of bottomright point
        public int Bottom; // Y coordinate of bottomright point
    }

若要查找X,Y坐标,请将以下内容输入到您的代码中(在rect中,您已请求坐标):

        IntPtr handle = (PresentationSource.FromVisual(popup.Child) as HwndSource).Handle;

        RECT rect = new RECT();
        GetWindowRect(handle, out rect);

此解决方案仅适用于Windows窗体和传统的Windows,不适用于WPF/Xaml。 - VoidVolker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接