我正在尝试获取弹出控件的X,Y坐标。我试过了:
VisualTreeHelper.GetOffset(弹出);
但返回的向量总是包含(0,0)X和Y.
弹出窗口的父级是布局根目录,即网格。
CustomPopupPlacementCallback也总是为它的Point参数返回0,0。
目标是允许用户将弹出窗口拖动到屏幕上的任何位置。我打算通过获取当前弹出窗口和鼠标位置,并以与鼠标移动方向相同的方向移动弹出窗口来尝试完成此操作。
--------------------更新--------------------
Chris Nicol,我已经使用以下代码尝试了您的答案,但仍然收到0,0 for rootPoint:
的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));
}
}
答案 0 :(得分:2)
不确定这是找出问题的最佳方法,但确实有效:
GeneralTransform transform = controlToFind.TransformToAncestor(TopLevelControl);
Point rootPoint = transform.Transform(new Point(0, 0));
答案 1 :(得分: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坐标将此输入到您的代码中(在矩形中您已请求坐标):
IntPtr handle = (PresentationSource.FromVisual(popup.Child) as HwndSource).Handle;
RECT rect = new RECT();
GetWindowRect(handle, out rect);