为什么不起作用?启动位置= WPF中的CenterOwner

时间:2019-07-09 04:08:34

标签: c# wpf

enter image description here

我想将子窗口定位到父窗口的中心。但是它在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不在CenterOwnerMainWindow

1 个答案:

答案 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会在“随机”位置打开。