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);
}
}
也许用Application.Current.Shutdown()
??
public void ExecuteExitCommand()
{
Application.Current.Shutdown();
}
使用Exception作为通信机制看起来很奇怪。
如果您不想在VM中调用ShutDown(),无论出于何种原因,使用Messenger
(在Prism中是EventAggregator
)发送自定义消息,您可以从应用程序类或主窗口的代码后面订阅并调用相同的Application.Current.Shutdown()
我个人喜欢这样做:
private DelegateCommand terminateApplication;
public ICommand TerminateApplication => terminateApplication ??= new
DelegateCommand(PerformTerminateApplication);
private void PerformTerminateApplication()
{
Environment.Exit(0);
}