WPF - 设置对话框窗口相对于主窗口的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2446602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:34:45  来源:igfitidea点击:

WPF - Set dialog window position relative to main window?

wpfpositionwindow

提问by empo

I'm just creating my own AboutBox and I'm calling it using Window.ShowDialog()

我只是在创建我自己的 AboutBox 并使用 Window.ShowDialog() 调用它

How do I get it to position relative to the main window, i.e. 20px from the top and centered?

我如何让它相对于主窗口定位,即距离顶部 20 像素并居中?

回答by gehho

You can simply use the Window.Leftand Window.Topproperties. Read them from your main window and assign the values (plus 20 px or whatever) to the AboutBox beforecalling the ShowDialog()method.

您可以简单地使用Window.LeftWindow.Top属性。调用该ShowDialog()方法之前,从主窗口读取它们并将值(加上 20 像素或其他值)分配给 AboutBox 。

AboutBox dialog = new AboutBox();
dialog.Top = mainWindow.Top + 20;

To have it centered, you can also simply use the WindowStartupLocationproperty. Set this to WindowStartupLocation.CenterOwner

要使其居中,您还可以简单地使用WindowStartupLocation属性。将此设置为WindowStartupLocation.CenterOwner

AboutBox dialog = new AboutBox();
dialog.Owner = Application.Current.MainWindow; // We must also set the owner for this to work.
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;

If you want it to be centered horizontally, but not vertically (i.e. fixed vertical location), you will have to do that in an EventHandler after the AboutBox has been loaded because you will need to calculate the horizontal position depending on the Width of the AboutBox, and this is only known after it has been loaded.

如果您希望它水平居中,而不是垂直居中(即固定垂直位置),则必须在加载 AboutBox 后在 EventHandler 中执行此操作,因为您需要根据 AboutBox 的宽度计算水平位置,这只有在加载后才知道。

protected override void OnInitialized(...)
{
    this.Left = this.Owner.Left + (this.Owner.Width - this.ActualWidth) / 2;
    this.Top = this.Owner.Top + 20;
}

gehho.

格霍。

回答by Li3ro

I would go the manual way, instead of count on WPF to make the calculation for me..

我会采用手动方式,而不是指望 WPF 为我进行计算。

System.Windows.Point positionFromScreen = this.ABC.PointToScreen(new System.Windows.Point(0, 0));
PresentationSource source = PresentationSource.FromVisual(this);
System.Windows.Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(positionFromScreen);

AboutBox.Top = targetPoints.Y - this.ABC.ActualHeight + 15;
AboutBox.Left = targetPoints.X - 55;

Where ABCis some UIElement within the parent window (could be Owner if you like..) , And could also be the window itself (top left point)..

ABC父窗口中的某个 UIElement 在哪里(如果您愿意,可以是 Owner..),也可以是窗口本身(左上角)。

Good luck

祝你好运