title: Exiting an App or Closing a Control When Using MVVM
body: <p>In my WPF application, I am using the <code>ViewModelLocator</code> without IoC.  I am calling the static <code>ViewModelLocator.Cleanup()</code> method provided by the MVVM-Light framework from my own button which is tied to a "close window command".  This Command calls the static <code>ViewModelLocator.Cleanup()</code>, which calls an instance Cleanup() method on my MainWindowViewModel instance.  The instance Cleanup() method then sets the property to which the MainWindow binds its <code>DataContext</code>, to null.  The setter on the property raises a <code>PropertyChanged</code> event.  Curiously, setting this property to null does not cause the window to close.</p>
  
  <p>I am trying to understand why this is the case?  If I set the MainWindow's <code>DataContext</code> to null, should that not be the same as <code>Window.Close()</code>?  In my case, the Window and all of its elements remain on the screen.  However, if I attempt further actions, I get null pointer exceptions, indicating the <code>DataContext</code> binding Property has indeed been set to null;  this has also been confirmed in the debugger.</p>
  
  <p>I have created a workaround by hooking the Application.Exit event and issuing a Window.Close() in the event handler in order to create my own "Close Window" button (ie, to create same functionality for my own Button / Command as clicking the X button in the upper right of a Window).  Since calling a UI element (ie, the Window instance) from MVVM directly is not MVVM friendly, I used a <a href="http://blog.synctank.com/2011/12/03/viewservice-present/" rel="nofollow">ViewService</a> to implement the Window.Close() functionality in order to keep the workaround MVVM friendly.  I am a big fan of the ViewService idiom (or pattern), but I just don't think it should be necessary here; except, I could see how exiting the app is a special case that perhaps should tie-in with the application lifecycle, and .Net seems to only allow exiting a WPF app by issuing the Window.Close() method.</p>
  
  <p>Thoughts appreciated.</p>