View-First(Xaml) vs ViewModel-First(DI via constructor)


How do you create Views and ViewModels.  The two approaches I hear most often are:

  • View-First: The View has a relationship to its ViewModel(usually through data binding).
  • ViewModel-First: The ViewModel creates the view (usually through an IoC container).

In View-First, it is usually is exemplified in XAML like so:

<UserControl x:Class="MVVM.Client.Views.GameView"
    <data:GamesViewModel x:Key="TheViewModel" />
  <Grid DataContext="{Binding Path=Games, Source={StaticResource TheViewModel}}">

In ViewModel-First, it is usually implemented using a Inversion of Control container (e.g. Unity, Ninject, Spring, etc.). This way the ViewModel can request the interface (in the constructor) for the View it expects:

public MyViewModel
  public MyViewModel(IMyView view)

In both of these methods it presents a sticky-ness of the view to the view-model. Also, both of these imply a one-to-one relationship which while the common case, is not the always case.

Shaw Wildermuth has come up with another pattern called  “Marriage”.

public interface IView
  void ApplyViewModel(object viewModel);

IView view = theContainer.Resolve<IGameView>();
IViewModel vm = theContainer.Resolve<IGameViewModel>();

Read more -> Shawn Wildermuth – Which came first, the View or the Model?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s