5

I'm trying to learn MVVM, but there is something I don't understand yet.

Currently, I have this event handler:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (MessageBox.Show("Are you sure you want to close this application?", "Close??", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
}

Very easy. However, I would like to apply the MVVM pattern in this application.

I'm wondering, am I supposed to put this logic in a ViewModel instead of directly in the view code? If so, how am I supposed to do that?

Thanks

Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
Bv202
  • 3,924
  • 13
  • 46
  • 80

1 Answers1

0

You can use your own ViewsService which can be used in ViewModel and interact with View. For example you can write method ViewsService.CloseActiveWindow(). In this case you don't need to interact with View directly from ViewModel but via service class.

Another way: using of global publish/subscribe service. ViewModel will send event and View will subscribe on this event. In case of multiple windows you can check is window active and close only active window.

Rover
  • 2,203
  • 3
  • 24
  • 44