WPF 窗口位置

6

之前我曾经问过一个有关创建子窗口的问题(链接在此)...现在当我打开子窗口时,它并没有居中于父窗口。如何设置让它居中于父窗口呢?

3个回答

19

这个方法对我很有效。

下面是我在WPF中找到的一种将窗口居中到其父窗口或应用程序主窗口的方法,它和WinForms中的方法相似。

对于子窗口,请将其WindowStartupLocation设置为“CenterOwner”。这将使其显示在拥有窗口的中心位置。

<Window x:Class="WpfApplication1.TestChild"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestChild" Height="300" Width="300"
    WindowStartupLocation="CenterOwner">

现在,唯一要做的就是在显示它之前设置它的所有者。如果用于显示窗口的代码运行在Window类内部,则可以直接使用this。

TestChild testWindow = new TestChild();
testWindow.Owner = this;
testWindow.Show();

但并非总是这样;有时,您需要从在页面或用户控件上运行的代码中显示子窗口。在这种情况下,您希望子窗口相对于应用程序的主窗口居中显示。

TestChild testWindow = new TestChild();
testWindow.Owner = Application.Current.MainWindow;
testWindow.Show();

1
你能否在回答中提供一个解决方案的示例?外部链接也可以,但最好即使其他互联网消失,Stack Overflow 仍可用。 - Merlyn Morgan-Graham

3
尝试 这个
aboutWindow.WindowStartupLocation= WindowStartupLocation.CenterOwner ; 

aboutWindow.ShowDialog(this); 

1
你可以尝试这个:
 AboutWindow window = new AboutWindow();
 window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
 window.Owner = this;

 window.ShowDialog();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接