How to close a WPF application from the context menu?

Is there a command in WPF to close the application from the context menu? That is, in the same context menu that you get by right-clicking on the title bar in any window?

There are many standard commands, but I'm trying to find the exit command.

+7
command wpf
source share
4 answers

Unfortunately, this does not exist. You will need to execute the user command and call

Application.Current.Shutdown(); 
+16
source share

There is ApplicationCommands.Close, but ApplicationCommands.Exit does not exist.

See this thread (for example) for alternatives (for example, creating a custom command).

+1
source share

Your problem has been resolved. But the following code may help others.

      Environment.Exit (0)
+1
source share

Not that complex actually (but still, M $ sucks in without providing it). Here you are:

 public static class MyCommands { private static readonly ICommand appCloseCmd = new ApplicationCloseCommand(); public static ICommand ApplicationCloseCommand { get { return appCloseCmd; } } } //=================================================================================================== public class ApplicationCloseCommand : ICommand { public event EventHandler CanExecuteChanged { // You may not need a body here at all... add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return Application.Current != null && Application.Current.MainWindow != null; } public void Execute(object parameter) { Application.Current.MainWindow.Close(); } } 

And the body of the AplicationCloseCommand.CanExecuteChanged event AplicationCloseCommand.CanExecuteChanged may not even be necessary.

You use it like this:

 <MenuItem Header="{DynamicResource MenuFileExit}" Command="MyNamespace:MyCommands.ApplicationCloseCommand"/> 

Hooray!

(You cannot imagine how long it took me to open this Command ... material)

0
source share

All Articles