Search code examples
.netwpfmvvmprism

Is this the right way to shutdown prism application without default exit button?


The window of app do not have boarder, so there is no exit button on the right conner?How can I close it in right way?

This is my way, fisrt bind a command to custom exit button.

<Button Content="Exit" HorizontalAlignment="Left" Margin="327,198,0,0" VerticalAlignment="Top" Width="75" Command="{Binding ExitCommand}"/>

Than throw a exception in a ViewModel when button clicked.

class ViewModel:NotificationObject
{
    public ViewModel()
    {
        this.ExitCommand = new DelegateCommand(new Action(this.ExecuteExitCommand));
    }

    public DelegateCommand ExitCommand { get; set; }

    public void ExecuteExitCommand()
    {
        throw new ApplicationException("shutdown");
    }
}

Catch the exception in Application class

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Bootstrapper bootstrapper = new Bootstrapper();
        AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
        try
        {
            bootstrapper.Run();
        }
        catch (Exception ex)
        {
            HandleException(ex);
        }
    }

    private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        HandleException(e.ExceptionObject as Exception);
    }

    private static void HandleException(Exception ex)
    {
        if (ex == null)
            return;
        Environment.Exit(1);
    }
}

Solution

  • Just maybe use Application.Current.Shutdown() ??

    public void ExecuteExitCommand()
    {
        Application.Current.Shutdown();
    }
    

    Using an Exception as a communication mechanism just seems weird.

    If you do not want to invoke ShutDown() in the VM for whatever reason, use a Messenger(in Prism that's EventAggregator) to send a custom message which you can subscribe from the Application Class or the MainWindow's code-behind and invoke the same Application.Current.Shutdown()