I am using WPF and MVVM Light framework (I am new in using them).
I want to do the following:
- When the user click on the ‘X’ close button, I want to display a confirmation window if whether he wants to exit the application or not.
- If yes, the application closes
- If no, nothing happens and he can still use the application as per normal
So far, I have this:
-
In MainWindow.xaml.cs:
public MainWindow() { InitializeComponent(); Closing += (s, e) => ViewModelLocator.Cleanup(); } -
In ViewModelLocator.cs:
public static void Cleanup() { ServiceLocator.Current.GetInstance<MainViewModel>().Cleanup(); } -
In MainViewModel.cs:
public override void Cleanup() { MessageBoxResult result = MessageBox.Show( "Unsaved data will be lost, would you like to exit?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { // clean-up resources and exit } else { // ???? }
Actually, if the user answers ‘Yes’ or ‘No’, in both cases the application will exit.
I am not too sure how to proceed from here…
Any help would be great!
Thanks
You can use an
EventToCommandin anEventTriggerto catch the closing event and set theCancelproperty of the passedCancelEventArgsto true if you want to cancel the closing:XAML:
ViewModel: