• Why Prism WPF applications closes when a non Shell window is closed?

    Published by on October 28th, 2009 10:54 pm under p&p, Patterns & Practices, Prism v2, Windows Presentation Foundation, WPF

    No Comments

    If you use Prism in your WPF applications, you will notice that the Shell window is usually the application’s main window. If you want to check it just execute in debug time Application.Current.MainWindow from the immediate window.

    In the Codeplex forum we received an interesting question that said that an application was being shutdown after its Login window was closed which was instantiated from the OnStartup method.

    The reason for this particular behavior is that WPF’s Window class has a property named ShutdownMode with default value OnLastWindowsClose. So if you instantiated a window before  instantiating any other window and close it, WPF implicitly calls Shutdown. This is because it is the first and unique window in the application lifetime so far.

    What happens if you have a similar scenario?. You can implement the two following approaches:

    • Instantiate the Login window after the Shell window, because in this way the Shell will be the last window and main windows at once, so the Shutdown method doesn’t be called after closes the Login window.
    • Choose to close the application explicitly. To do this, you must set the ShutdownMode with the value  OnExplicitShutdown, which requires an explicit Shutdown method call to stop the application.

    Demonstration

    You can find in this zip file the following two applications which shows how it works:

    • ClosingSolution: The application closes after closing the Login window.
    • NotClosingSolution: The application closes explicitly.

    Note: The code I provided doest not follow the best practices, it’s just for demo purposes.

    I hope you can find this post useful.

    Tags: , , , ,

About


Follow me on Twitter

Categories

Archives

Map