Sunday, January 16, 2011

WPF - Main Window disappears when closing the last owned child window

Today I witnessed a weird thing with WPF
Itay, a very good friend of mine noticed that when you have multiple child windows in a WPF application, and you close the last one, the application suddenly disappears,
This only happens if you have more than one child window and you set the MainWindow as the owner of the other windows
This is a very unexpected behavior.
Let me demonstrate
The following code is in the MainWindow.xaml.cs

private void ShowChildWindows()
{
   ChildWindow window = new ChildWindow() { Owner = this };
   window.Show();
   window = new ChildWindow() { Owner = this };
   window.Show();
}

Once I close both of the windows mentioned above, the MainWindow is hidden away for some reason.
The workaround to this problem is to detect that you are closing the last window and remove the owner of that child window.
For example:

private void ShowChildWindowsFixedVersion()
{
   ChildWindow window = new ChildWindow() { Owner = this };
   window.Closing += window_Closing;
   window.Show();
   window = new ChildWindow() { Owner = this };
   window.Closing += window_Closing;
   window.Show();
}
void window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   var child = sender as Window;

Read more: Tal Pasi