Reputation: 193282
In a WPF application, I have buttons which pop up instances of windows.
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?
Upvotes: 2
Views: 12373
Reputation: 334
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();
Upvotes: 6
Reputation: 106796
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();
}
Upvotes: 12