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


image

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"
             ...
             xmlns:data="clr-namespace:MVVM.Client.Data;assembly=MVVM.Client.Data">
  <UserControl.Resources>
    <data:GamesViewModel x:Key="TheViewModel" />
  </UserControl.Resources>
  <Grid DataContext="{Binding Path=Games, Source={StaticResource TheViewModel}}">
  ...
  </Grid>
</UserControl>

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>();
view.ApplyViewModel(vm);

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s