Search code examples
wpfdialogwindowminimize

Closing child window minimizes parent


The following code demonstrates an issue I'm having where closing a child window minimizes the parent window, which I dont want to happen.

    class SomeDialog : Window
    {
        protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
        {
            base.OnMouseDoubleClick(e);
            new CustomMessageBox().ShowDialog();
        } 
    }

    class CustomMessageBox : Window
    {
        public CustomMessageBox()
        {
            Owner = Application.Current.MainWindow;
        }
    }

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
        {
            base.OnMouseDoubleClick(e);
            new SomeDialog() { Owner = this }.Show();
        }
    }

Window1 is the main application window.

SomeDialog is a window that pops up on some event within Window1(double clicking window1 in the example) that needs to be modeless.

CustomMessageBox is a window that pops up on some event within "SomeDialog" (double clicking SomeDialog in the example) that needs to be modal.

If you run the application, and then double click Window1's content to bring up SomeDialog, and then you then double click SomeDialog's content to bring up the CustomMessagebox.

Now you close CustomMessagebox. Fine.

Now if you close SomeDialog, Window1 minimizes? Why is it minimizing and how can I stop it?

Edit : It appears the workaround is rather simple, using the technique suggesrted by Viv.

class SomeDialog : Window
    {
        protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
        {
            base.OnMouseDoubleClick(e);
            new CustomMessageBox().ShowDialog();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);
            Owner = null;
        }
    }

Solution

  • Why is it minimizing and how can I stop it?

    Not sure about the "Why" maybe you can report it as a bug and see what they reply with as with a non-modal dialog you do not expect this to happen.

    As for a workaround, Try something like this:

    public partial class MainWindow : Window {
      ...
    
      protected override void OnMouseDoubleClick(MouseButtonEventArgs e) {
        base.OnMouseDoubleClick(e);
        var x = new SomeDialog { Owner = this };        
        x.Closing += (sender, args) => {
          var window = sender as Window;
          if (window != null)
            window.Owner = null;
        };
        x.Show();
      }
    }
    

    ^^ This should prevent the MainWindow(parent) from minimizing when SomeDialog is closed.