我想将子窗口定位到父窗口的中心。但是它在WPF中不起作用。
我设置了StartupLocation = CenterOwner
。但这不起作用。
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Task.Run(async () =>
{
await Task.Delay(1000);
Dispatcher.Invoke(() => new TestWindow().ShowDialog());
});
}
}
MainWindow.xaml
<Window x:Class="WpfApp29.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp29"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
TestWindow.xaml.cs
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
}
}
TestWindow.xaml
<Window x:Class="WpfApp29.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp29"
WindowStartupLocation="CenterOwner"
mc:Ignorable="d"
Title="TestWindow" Height="300" Width="300">
<Grid>
</Grid>
</Window>
我在ShowDialog
中调用MainWindow
函数。但是Testwindow
不在CenterOwner
(MainWindow
)
答案 0 :(得分:5)
您必须将TestWindow的Owner
设置为MainWindow,例如:
Task.Run(async () =>
{
await Task.Delay(1000);
Dispatcher.Invoke(() =>
{
TestWindow testWindow = new TestWindow();
testWindow.Owner = this;
testWindow.ShowDialog();
});
});
否则,您的TestWindow的所有者为null,然后TestWindow会在“随机”位置打开。