2010-01-12 28 views
6

我正在試圖獲取彈出控件的X,Y座標。我曾嘗試過:WPF彈出控件 - 查找X,Y座標

VisualTreeHelper.GetOffset(Popup);

但矢量返回的總是包含(0,0)爲X和Y

彈出的父是佈局根,這是一個網格。

CustomPopupPlacementCallback對於Point參數也總是返回0,0。

目標是允許用戶在屏幕上的任何位置拖動彈出窗口。我將嘗試通過獲取當前的彈出窗口和鼠標位置來完成此操作,並將鼠標移動到與鼠標相同的方向。

--------------------更新--------------------

Chris尼科爾,我試圖用下面的代碼你的答案,但仍然收到0,0 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

我有同樣的問題,你有沒有找到解決辦法?親切的問候 – Cinaird

+0

我沒有找到解決方案。對不起,延遲很長。 – gamzu07

+0

好的,謝謝你的回覆 – Cinaird

回答

2

不知道這是找出適合自己的最佳方式,但它的工作:

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

是的,那是最好的辦法。我通常在一行中做:'controlToFind.TransformToAncestor(TopLevelControl).Transform(new Point(0,0))' –

+0

yup,同樣,我在一行中做。我只是將它分開以便更容易理解 –

+0

感謝您的幫助,如果您有時間,請檢查我的更新。 – gamzu07

2

您必須使用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);