之前我曾经问过一个有关创建子窗口的问题(链接在此)...现在当我打开子窗口时,它并没有居中于父窗口。如何设置让它居中于父窗口呢?
这个方法对我很有效。
下面是我在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();
aboutWindow.WindowStartupLocation= WindowStartupLocation.CenterOwner ;
aboutWindow.ShowDialog(this);
AboutWindow window = new AboutWindow();
window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
window.Owner = this;
window.ShowDialog();