Skip to content
Antony Male edited this page Aug 2, 2014 · 8 revisions

In a traditional View-first approach, if you want to display a new window or dialog, you create a new instance of the View, then call .Show() or .ShowDialog().

In a ViewModel-first approach, you can't interact directly with the views, so you can't do this. The WindowManager solves this problem - calling IWindowManager.ShowWindow(someViewModel) will stitch the View's model onto that ViewModle, and display it.

class SomeViewModel
{
   private IWindowManager windowManager;
   public SomeViewModel(IWindowManager windowManager)
   {
      this.windowManager = windowManager;
   }

   public void ShowAWindow()
   {
      var viewModel = new OtherViewModel();
      this.windowManager.ShowWindow(viewModel);
   }

   public void ShowADialog()
   {
      var viewModel = new OtherViewModel();
      bool? result = this.windowManager.ShowDialog(viewModel);
      // result holds the return value of Window.ShowDialog()
      if (result.GetValueOrDefault(true))
         // DialogResult was set to true
   }
}

Nice and easy! In addition, the introduction of the IWindowManager (rather than calling methods directly on the ViewModel) makes testing a lot easier.

To close a window or dialog from its ViewModel, use Screen.TryClose, like this:

class ViewModelDispayedAsWindow
{
   // Called by pressing the 'close' button
   public void Close()
   {
      this.TryClose();
   }
}

class ViewModelDisplayedAsDialog
{
   // Called by pressing the 'OK' button
   public void CloseWithSuccess()
   {
      this.TryClose(true);
   }
}
Clone this wiki locally