How to make WPF pop-up windows not be hidden behin

2020-07-28 03:08发布

问题:

In a WPF application, I have buttons which pop up instances of windows.

  • I click the first button and the first window pops up correctly in front of the main application.
  • I click the second button and the second window pops up correct in front of the main application. However, the first window now moves behind the main application. This is confusing and unexpected since it is often in the middle of the main application and thus seems that it disappears until the user moves the main application to find it hiding behind.

This is the XAML:

<Window x:Class="TestPopupFix.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="600" Width="800">
    <StackPanel>
        <Button Content="Open first popup" Click="Button_OpenFirst"/>
        <Button Content="Open second popup" Click="Button_OpenSecond"/>
    </StackPanel>
</Window>

And this the code behind:

private void Button_OpenFirst(object sender, RoutedEventArgs e)
{
    Window window = new Window();
    TextBlock tb = new TextBlock();
    tb.Text = "This is the first window.";
    window.Content = tb;
    window.Width = 300;
    window.Height = 300;
    window.Show();
}

private void Button_OpenSecond(object sender, RoutedEventArgs e)
{
    Window window = new Window();
    TextBlock tb = new TextBlock();
    tb.Text = "This is the second window.";
    window.Content = tb;
    window.Width = 300;
    window.Height = 300;
    window.Show();
}

What do I have to do to make the main application stay furthest to the back as I pop up new windows?

回答1:

To arrange windows in a visual hierarchy you have to set the Owner property of the child window to the parent window.

You can read more about the Owner property on MSDN.

You should change your code into something similar to this:

Window parentWindow;

private void Button_OpenFirst(object sender, RoutedEventArgs e)
{
  this.parentWindow = new Window();
  this.parentWindow.Owner = this;
  this.parentWindow.Show();
}

private void Button_OpenSecond(object sender, RoutedEventArgs e)
{
  Window childWindow = new Window();
  childWindow.Owner = this.parentWindow;
  childWindow.Show();
}


回答2:

I had the same problem, but hosting a WPF window in a WinForms form. In this situation, setting the owner got me part of the way, but occasionally it was still going behind.

What I ended up doing in addition to that was wiring up the Loaded event on the WPF window and calling Activate as follows:

_window.Loaded += (s, e) => _window.Activate();


标签: c# wpf xaml popup