title: Window.Closing event handler in MVVM
body: <p><em>Following question is based on comment in this post: <a href="https://stackoverflow.com/a/32248041/475727">MVVM Understanding Issues</a></em></p>
  
  <p>I said that this is codebehind, that does not violate the view and viewmodel separation of concerns:</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
  
          Closing += MainWindow_Closing;
      }
  
      void MainWindow_Closing(object sender, CancelEventArgs e)
      {
          var canExit = ViewModel.ShowConfirmExitDlg();
          if (!canExit) e.Cancel = true;
      }
  }
  </code></pre>
  
  <p>The comments was:</p>
  
  <blockquote>
    <p>Anything in code-behind can't be unit tested, and invoking the
    creation of a dialog box is logic and therefore shouldn't be in the
    view</p>
  </blockquote>
  
  <p>I have two questions: </p>
  
  <ol>
  <li><strong>Does this break MVVM separation of conerns?</strong></li>
  <li><strong>How would you do it (better)</strong>? </li>
  </ol>
  
   <hr />
  
  <p>I could call the viewmodel method from xaml using some EventTriggers and CallMethod actions, but it does not make any difference.</p>
  
  <p>I could do use event aggregator:</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      private readonly IEventAggregator _eventAggregator;
  
      public MainWindow(IEventAggregator eventAggregator)
      {
          _eventAggregator = eventAggregator;
          InitializeComponent();
  
          Closing += MainWindow_Closing;
      }
  
      void MainWindow_Closing(object sender, CancelEventArgs e)
      {
          var evt = new MainWindowClosingEvent();
          _eventAggregator.Publish(evt);
          e.Cancel = evt.IsCancel;
      }
  }
  </code></pre>
  
  <p>and handle the event in viewmodel but does it bring any value? I still cannot unit test cancelling the windows closing event, but I have introduces publishing and subscribing that would be also worth unittestig. It's yet another layer of indirection</p>
  
  <p>Maybe I could route the event to viewmodel:</p>
  
  <pre><code>public MainWindow()
  {
     InitializeComponent();
     Closing += ViewModel.OnWindowClosing;
     //or
     Closing += (o, e) =&gt; ViewModel.OnWindowClosing(e);
  }
  </code></pre>
  
  <p>but I don't see much difference with the original sample. </p>
  
  <p>IMHO, the connection between view and viewmodel cannot be unittested in viewmodel tests, so I either find a way how to test views or it is wild goose chase.</p>