View-first and ViewModel-first

The MVVM design pattern was developed by Microsoft as a variation of the Martin Fowler’s Presentation Model pattern – we’ll copy/paste here the short form of the motivations behind this pattern (the long form is available in the link above):

  • It provides separation of concerns.
  • It is a natural pattern for XAML platforms.
  • It enables a developer-designer workflow.
  • It increases application testability.
they are all true but we’d like here just to sketch how this pattern can be used in two of its variations.

View-first

The View-first form can be used when the view is available at design time: the developer is able to design the user interface and connect it immediately to the ViewModel.
The ViewModel is usually a class that derives from DependencyObject or implements INotifyPropertyChanged (if it’s a POCO object):

 

 

The View can instantiate the ViewModel in its resources:

 

 

we generally want to keep clean the code behind but in this case it is fine to expose the ViewModel so that it can be accessed from the instance of the View:

 

 

The View creates at design time the ViewModel that will be its DataContext.

ViewModel-first

The View-first is fine when the view can be directly created at runtime but sometimes we have to deal with situations in which a set of classes that are ViewModels are available “at a given time” and a View must be able to show the data they contains.
We call this case ViewModel-first because the ViewModel is created (or is available) first and a View must be provided, somehow, to show their content.
In that case we can provide a placeholder through the ContentPresenter widget:

 

 

A “set of Views” can be created (for example in the app Resources) using DataTemplates designed around the various ViewModel types:

 

 

at runtime, the ViewModel itself can pick-up the correct View and initialize the part of the interface that is designed around it:

 

 

Of course, we can find a better way to fill the ContentPresenter instead of directly assigning Content/ContentPresenter but this is a detail – the important thing is that in this case, it’s up to the ViewModel to retrieve the View (the correct DataTemplate) that is able to render itself and thus, through a “selector”, we can generate dynamic Views (or part of a View) starting from a unique agnostic container.

Leave a Reply

Your email address will not be published. Required fields are marked *