WPF - 设置相对于用户控件的对话窗口位置

时间:2017-05-22 17:55:47

标签: c# wpf user-controls location

我需要帮助设置相对于用户控件的对话框窗口位置。

我想在窗口启动时在中间用户控件中显示我的窗口。

如何找到用户控件的左侧和tom位置?

我在我的应用中使用此代码但在WPF中无法正常工作。

感谢您的帮助。

     private void PossitionWindow(object sender, RoutedEventArgs e)
      {
        Window wind = new Window();

        var location = this.PointToScreen(new Point(0, 0));
        wind.Left = location.X;
        wind.Top = location.Y - wind.Height;
        location.X = wind.Top + (wind.Height - this.ActualHeight) / 2;
        location.Y = wind.Left + (wind.Width - this.ActualWidth) / 2;
    }

1 个答案:

答案 0 :(得分:0)

这是一个小例子。

// Get absolute location on screen of upper left corner of the UserControl
Point locationFromScreen =  userControl1.PointToScreen(new Point(0, 0));

// Transform screen point to WPF device independent point
PresentationSource source = PresentationSource.FromVisual(this);
Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(locationFromScreen);

// Get Focus
Point focus = new Point();
focus.X = targetPoints.X + (userControl1.Width / 2.0);
focus.Y = targetPoints.Y + (userControl1.Height / 2.0);

// Set coordinates

Window window = new Window();
window.Width = 300;
window.Height = 300;
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Top = focus.Y - (window.Width / 2.0);
window.Left = focus.X - (window.Height / 2.0);

window.ShowDialog();

预览

preview