ViewModel Locator in WPF

The ViewModel locator allows you to select which ViewModel is going to the view. You can take advantage of this design to even load different ViewModels by dependency injection. A ViewModelLocator is a class witch will map ViewModels to its properties and on your views you can specify which ViewModel it should use.

It also allows you to use a different ViewModel during design time so you can see mock values when you are building the views.

An example of a ViewModelLocator would be the following:

  1. public class ViewModelLocator   
  2. {   
  3.    private DependencyObject dummy = new DependencyObject();   
  4.   
  5.    public IMainViewModel MainViewModel   
  6.    {   
  7.       get   
  8.       {   
  9.          if (IsInDesignMode())   
  10.          {   
  11.             return new MockMainViewModel();   
  12.          }   
  13.   
  14.          return MefBootstrap.Container.GetExportedValue<IMainViewModel>();   
  15.       }   
  16.    }   
  17.   
  18.    private bool IsInDesignMode()   
  19.    {   
  20.       return DesignerProperties.GetIsInDesignMode(dummy);   
  21.    }   
  22. }   
An AndApp.xaml file you could include as a resource. Define the namespace on the class above and register it on the resources.
  1. xmlns:core="clr-namespace:YourNameSpace"   
  2.   
  3. <Application.Resources>   
  4.    <core:ViewModelLocator x:Key="ViewModelLocator" />   
  5. </Application.Resources>   
With the locator in your application resources you can refer to it as `{StaticResource ViewModelLocator}` anywhere in your application.

On your view you can then bind the DataContext to a property of the locator as in the following:
  1. <Window x:Class="WpfGuide.Views.MainView"   
  2.    ...   
  3.    DataContext="{Binding Path=MainViewModel,   
  4.    Source={StaticResource ViewModelLocator}}"   
  5. >   
With the example above I will have a mock ViewModel when I'm designing the application as in the following:

main window

And real values when I'm running it as in the following:

run app

 

Up Next
    Ebook Download
    View all
    Learn
    View all