How do I make WPF popups not hide behind the main application?

In a WPF application, I have buttons that expose windows instances.

  • I click the first button and the first window appears correctly in the front of the main application.
  • I click the second button and the second window appears correctly in the front of the main application. However, the first window now moves behind the main application. This is confusing and unexpected, as it is often in the middle of the main application, and thus seems to disappear until the user moves the main application to find it hiding.

alt text http://i28.tinypic.com/jqjkfp.jpg

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 code :

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 need to do to keep the main application farthest in the opposite direction when new windows appear?

+2


source to share


2 answers


To arrange windows in a visual hierarchy, you must set the Owner

child window property to the parent window.

You can read more about the property Owner

at MSDN
.



You should change your code to 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();
}

      

+12


source


I had the same problem, but I found a WPF window in WinForms. In this situation, setting the owner gave me some of the way, but sometimes it still lagged behind.

What I ended up doing, besides this, was to hook up the event Loaded

in the WPF window and call it Activate

like this:



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

      

+6


source







All Articles