WPF-设置对话框窗口相对于主窗口的位置? [英] WPF - Set dialog window position relative to main window?

查看:684
本文介绍了WPF-设置对话框窗口相对于主窗口的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何使其相对于主窗口定位,即从顶部居中20px?

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

推荐答案

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

You can simply use the Window.Left and Window.Top properties. Read them from your main window and assign the values (plus 20 px or whatever) to the AboutBox before calling the ShowDialog() method.

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

要使其居中,也可以只使用 WindowStartupLocation 属性.将此设置为 WindowStartupLocation.CenterOwner

To have it centered, you can also simply use the WindowStartupLocation property. Set this to 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;

如果要使其水平居中,而不要垂直居中(即固定的垂直位置),则必须在AboutBox加载后在EventHandler中执行此操作,因为您需要根据Width来计算水平位置AboutBox,只有在加载后才知道.

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.

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

哥.

这篇关于WPF-设置对话框窗口相对于主窗口的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆