Nicholas Hill
Nicholas Hill

Reputation: 316

How do I show windows sequentially in WPF?

I have the following code in App.xaml.cs:

    protected override void OnStartup(StartupEventArgs e)
        {
        var window = new WelcomeWindow();
        if (window.ShowDialog() == true)
            {
            var mainWindow = new MainWindow();
            mainWindow.ShowDialog();
            }
        }

The second window never shows. Instead, the application simply closes when the Welcome window is closed. How do I ensure a second window can be shown after a first one is closed?

Upvotes: 3

Views: 136

Answers (2)

LPL
LPL

Reputation: 17063

This is because default value of Application.ShutdownMode is OnLastWindowClose. This means when your WelcomeWindow is closed the application shuts down and you see nothing more.

To solve this set ShutdownMode to OnExplicitShutdown and call Shutdown explicitly if you want to exit your app.

public App()
{
    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}

Upvotes: 4

potehin143
potehin143

Reputation: 531

What about to show WelcomeWindow on Initialized event of MainWindow and close last if Dialog is not true. This was you let MainWindow to stay the MainWindow of Application.

    private void Window_Initialized(object sender, EventArgs e)
    {
        // at this moment MainWindow is Initialized but still nonvisible
        if ((new WelcomeWindow()).ShowDialog()!=true)
        {
            this.Close();
        }
    }

When you load any window Application_Startup it become The MainWindow of application. And it will closed on this window closing. I've checked that even if you have StartupUri="MainWindow.xaml" in you app.xaml it have no effect if some else window have been shown on Application StartUp event. You may do it yourself. Just make breakpoint on your firstloaded window Loaded event handler and look in debuger on "Aplication.Current.MainWindow == this" expression result. It will be true.

Upvotes: 1

Related Questions