Ole M
Ole M

Reputation: 347

WPF: How to keep parent window open OR re-opening it when I close all windows?

Hello!

In my WPF-app, when I am in my 2nd or 3rd child-window, I have a 'Log out'-button. When it's pressed, I want all open windows to be closed, and the parent window (LoginScreen) to be re-opened. Alternatively, a restart of the entire application. Either one is fine.

P.S.: I am not interested in implementing a MVVM-navigation system (I'll leave that for my next project).

Currently, I am closing all open windows with the following code:

private void CloseAllWindows()
      {
         for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
            App.Current.Windows[intCounter].Close();
      }

But I do not know how to keep, or re-open, the LoginScreen-window.

What I've tried:

If I'm in the first child form, just re-instantiating the LoginScreen-window works well. But I need a work-around for when I'm deeper in the application.

I tried:

Process.Start(Application.ResourceAssembly.Location);
Application.Current.Shutdown();

It does not work.

Implementing System.Windows.Forms and using the Application.Restart() method doesn't work either. I get a red squiggly line, even though others profess to get it working. Any tips for a work-around?

Thanks!

Upvotes: 1

Views: 537

Answers (1)

Clemens
Clemens

Reputation: 128013

This method closes all Windows except the MainWindow:

private static void CloseAllWindowsExceptMainWindow()
{
    Application.Current.Windows
        .Cast<Window>()
        .Where(w => w != Application.Current.MainWindow)
        .ToList()
        .ForEach(w => w.Close());
}

You may change the comparison in Where in case you want to keep some other specific Window open, for example:

private static void CloseAllWindowsExceptLoginScreen()
{
    Application.Current.Windows
        .Cast<Window>()
        .Where(w => !(w is LoginScreen))
        .ToList()
        .ForEach(w => w.Close());
}

Upvotes: 3

Related Questions