【问题标题】:Is this the right way to shutdown prism application without default exit button?这是在没有默认退出按钮的情况下关闭 prism 应用程序的正确方法吗?
【发布时间】:2026-01-08 20:05:03
【问题描述】:

app的窗口没有边框,所以右角没有退出按钮?如何正确关闭?

这是我的方式,首先将命令绑定到自定义退出按钮。

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

比单击按钮时在 ViewModel 中引发异常。

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");
    }
}

在应用程序类中捕获异常

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);
    }
}

【问题讨论】:

    标签: .net wpf mvvm prism


    【解决方案1】:

    也许可以使用Application.Current.Shutdown() ??

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

    使用异常作为通信机制似乎很奇怪。

    如果您出于某种原因不想在 VM 中调用 ShutDown(),请使用 Messenger(在 Prism 中为 EventAggregator)发送自定义消息,您可以从应用程序类或 MainWindow 的代码订阅该消息-在后面调用相同的Application.Current.Shutdown()

    【讨论】:

    • 作为一种通信机制的异常看起来很奇怪,直到你有一个未处理的异常。
    【解决方案2】:

    我个人喜欢这样做:

    private DelegateCommand terminateApplication;
    public ICommand TerminateApplication => terminateApplication ??= new 
    DelegateCommand(PerformTerminateApplication);
    
    private void PerformTerminateApplication()
    {
        Environment.Exit(0);
    }
    

    【讨论】:

      最近更新 更多