Callback from the dialog window to the main window

I am developing an MVVM WPF application using MVVMLightToolkit as a third-party helper. My scenario is as follows:

I have a main window and, closing the main window, I have to show a new dialog box (save the change dialog box) to confirm that it should save the changes that it made in the application, the status file or not . How can I handle this scenario in MVVM ?. I usually use the MVVMLight Messenger class to display a new window. In this case, I open the Save Changes window from the main window . I need a callback to the Main View model based on the selected user option (SAVE, SAVE / EXIT, CANCEL) from the Save Changes dialog box and based on this I must check whether I should close the main window or not. What would be the best MVVM approach to handle this scenario?

+4
source share
2 answers

Just pass messages from / to the ViewModel.

View

private void Window_Closing(object sender, CancelEventArgs e) { Messenger.Default.Send(new WindowRequestsClosingMessage( this, null, result => { if (!result) e.Cancel = true; }); } 

ViewModel

 Messenger.Default.Register<WindowRequestsClosingMessage>( this, msg => { // Your logic before close if (CanClose) msg.Execute(true); else msg.Execute(false); }); 

Message

 public class WindowRequestsClosingMessage: NotificationMessageAction<bool> { public WindowRequestsClosingMessage(string notification, Action<bool> callback) : base(notification, callback) { } public WindowRequestsClosingMessage(object sender, string notification, Action<bool> callback) : base(sender, notification, callback) { } public WindowRequestsClosingMessage(object sender, object target, string notification, Action<bool> callback) : base(sender, target, notification, callback) { } } 

MVVM Light NotificationMessageAction <TResult> allows you to send a message and get a result of type TResult. To pass TResult back to the requestor, call Execute() exactly the same way as in the example.

+1
source

Why don't you do something like the following in your closure:

  private void Window_Closing(object sender, CancelEventArgs e) { SaveDialog sd = new SaveDialog(); if (sd.ShowDialog() == false) { e.Cancel = true; } } 
0
source

All Articles