WELCOME

This blog is where I post about my consulting work with Microsoft Technologies, and other random tidbits that don't fit in my Photo Blog or my Iraq Blog.

Thursday, June 11, 2009

MVVM Questions: Can a View Model close a window and other puzzlers

Many sample WPF applications written using MVVM (Model - View - View Model) only use a single Window, but the LOB (Line Of Business) applications I’ve been working on use LOTS of windows for different business tasks, and this has brought up a number of interesting questions about the “right” or “best” or “most practical” way to manage multiple Windows in a WPF application using MVVM?

Questions:

  1. Does a Window create it’s View Model?
  2. Or does the View Model create it’s Window?
  3. Or does “something else” create the View Model and the Window and then bind them together?
  4. How do you close a Window? 
  5. Can a View Model close itself and it’s Window?

Our Answers:

  1. We created a “Window Service” which is basically a Singleton with a Dictionary of all the open Windows and View Models in the application, and a few related methods to deal with opening and closing Windows .
  2. To open a Window you supply the Window Service with Window and a View Model.  The Window Service deals with binding the two together, showing  the Window, and then keeping track of the open Windows.
  3. If a user (or something else) tries to close a Window we catch the Window_Closing event  using AttachedCommandBehavior (see XAML below) and call a command on the View Model Base Class to give the View Model control over the closing event.
    <acb:CommandBehaviorCollection.Behaviors>
    <acb:BehaviorBinding Event="Initialized" Command="{Binding Path=Window_InitializedCommand}" />
    <acb:BehaviorBinding Event="Activated" Command="{Binding Path=Window_ActivatedCommand}" />
    <acb:BehaviorBinding Event="Closing" Command="{Binding Path=Window_ClosingCommand}" />
    </acb:CommandBehaviorCollection.Behaviors>



  4. View Models have the ability to close themselves (and their related Window) by calling the Window Service.

No comments: