Design – How to do to create the ViewModel part of your MVVM designs

designdesign-patternsmvvmuml

Sometimes, when I plan to create a program using this architectural pattern, I've got a lot of difficulties when I'm in the View Model phase.

I'm using WAF Framework to develop this architectural pattern. I'm a still a newbie.

Before you start, do you create all the UML design or do you use another tool to help you? How do you handle the design of your ViewModels ?

Best Answer

The ViewModel is an abstraction of the View.

That means you need to know first what you want to diplay to the user. At least you should have a detailled sketch of what the UI will look like (There are many tools intended to do this: MS Expression Blend, Balsamiq, etc.). Or even a dummy UI without logic plugged behind, created with your development tool.

Once you have your view, the ViewModel will be the place to hold every binded value, and what could be called display logic, mainly formatting. A View Model can be a representation of one Model, a group of Models of the same type, or an aggregation of different models.

A simple exemple of View Model is the editing screen with a drop down list. Let's have a concrete example with a User that can be linked to a division :

public class UserModel 
{ 
   public string Username { get; set; } 
   public string EmailAddress { get; set; } 
   public int DivisionId { get; set; } 
} 

public class DivisionModel 
{ 
   public int DivisionId { get; set; } 
   public string DivisionName { get; set; } 
} 

It wouldn't make sense to plug an IEnumerable of divisions in UserModel, so we create a View Model to represent a displayable User, with all the data needed to have a working screen where I can select a Division for that User :

public class UserViewModel 
{ 
   public UserModel User { get; set; } 
   public IEnumerable<DivisionModel> Divisions {get; set;} 
} 

And that's it. Depending on the language I'll be using, I'll just have to feed a drop down list with the IEnumerable of DivisionModels and make it show the Name member.