Tuesday, 8 April 2008

DataModel-View-ViewModel in WPF. Part 2 View and ViewModel.

This is the second part on my DataModel-View-ViewModel overview. In the previous part I was talking about DM classes which are intended to supply presentation layer that is composed of the View and ViewModel with data. Let's look at this View and ViewModel.

View

View is just a view (a xaml + codebehind class) and nothing more. It shouldn't keep any state or implement any logic operations except ones that relates to rendering.

VM doesn't "know" the view class and "speaks" with it through the IView interface. As I've mentioned earlier VM doesn't let you to switch UI framework without code review as ViewModel is tightly coupled with WPF-specific entities (such as commands), so for simplicity's sake I've promoted a IWPFView interface that consists of WPF-specific properties and events.



ViewModel

And at last main trinity's player. This class keeps all view related logic and state. My base VM class is parameterized vith view interface and it's descendant is parameterized with DM interface. Using CAB's IoC-container I resolve all of VM dependencies and inject it (VM) into View.



This classes have a bunch of useful virtual methods that are fired when View/DataModel set/unset events happen, in DataModel Loaded/ExceptionCatched events and View's Loaded/Unloaded. In a base class VM sets itself to a view's DataContext property, thus enabling it to update itself by DM, business objects and VM change events catching in databinding. So, speaking in Martin Fowler's words view in WPF is an ActiveView.


You can also find an ActionsViewModel on the diagram above. This class keeps a CommandModel objects list (very useful approach to wrap wpf command from Dan Crevier). For every command VM creates a command binding in a view automaticly.

ViewModel doesn't prohibit you from editing business object supplied by DM in UI and doesn't makes any validations of unedrlying data. So to avoid errors of this kind all of my objects are being edited in wizard UI (I've written a custom WPF control for it. I'll propably write about it later) that tracks object state and avoids saving invalid objects. But if you want to edit objects in your UI in a simple way you propably should read this article from Pete W.

That is all on View and ViewModel. In next part I'll assemble a simple example and (as I promised before) I'll include a sample code.

Good luck!

No comments: