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:
- Does a Window create it’s View Model?
- Or does the View Model create it’s Window?
- Or does “something else” create the View Model and the Window and then bind them together?
- How do you close a Window?
- Can a View Model close itself and it’s Window?
Our Answers:
- 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 .
- 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.
- 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>
- View Models have the ability to close themselves (and their related Window) by calling the Window Service.
No comments:
Post a Comment