вторник, 8 апреля 2008 г.

DataModel-View-ViewModel in WPF. Part 3 Example.

This is the last part on DM-V-VM pattern overview. In this part we'll write a simple WPF application built on this pattern.


Let's suppose that we have an object of class Foo that is provided by the SEModel class (parameterized with Foo and FooProvider types). It will be a demonstration of simplicity that SEModel gives - we don't have to write datamodel class, only provider class will be written.

All the logic is contained in a FooViewModel class. It is derived from ActionsViewModel as we'll have some actions triggers in UI (buttons). The actions are represented by two CommandModels - IncCommandModel and DecCommandModel. IncCommandModel increments Foo.Bar property when executed and DecCommandModel decrements it respectively. The DataModel is asked to refresh on View's Load event. DataModel will fetch data asyncronously and throw an event on UI thread as described in a first post

CommandModel classes implements logic for editing underlying data (Foo object) that is referenced in CommandParameter property of UI command triggers (objects that implement ICommandSource interface - Buttons in our example).

Now it is a view's turn.

In this example we won't use an IoC-container and will hardcode all dependecies in our classes. View creates ViewModel on it's Initialized event.

And keeping in mind that ViewModel sets itself to the DataContext property of View (window in our case) we know that all visual tree of our view will inherit VM in DataContext property. So just put a ContentControl in a view, bind it's Content property to VM and write a template to render VM.

The only evil SEModel can bring - is lack of ability to bind to it's Entity property. DataBinding just can't fetch the object even if all paths are accurate in 2 or more level templates. But this issue can be avoided easily - just put your object in View's resources in DataModelLoaded event in ViewModel and reference it in Binding via Source property.

This is how our application looks like:

Source for download: here.

Good luck!

PS: PnP group will finish their new project called - Prism, soon. It is intended to become CAB's replacement in developing LOB applications with WPF. Check for weekly drops here.

3 комментария:

Zoltan комментирует...


I read your articles about the DataModel-Veiw-ViewModel in WPF and I like them, they are very informative with nice links.
I was about to download the sample code that you included but unfrtunatly the link dosn't work anymore.
Please, can I ask you to upload it again, it would be

RobertT комментирует...

Hi, zoltan!
I'm glad to hear that you've found my writings intersting! I will reupload all stuff in a couple of days into a more durable store.

Zoltan комментирует...

Thx :)