ViewModel Locator

A ViewModelLocator is a class witch is going to 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 while you are building the views.

An example of a ViewModelLocator would be:
public class ViewModelLocator
{
    private DependencyObject dummy = new DependencyObject();

    public IMainViewModel MainViewModel
    {
        get
        {
            if (IsInDesignMode())
            {
                return new MockMainViewModel();
            }

            return MefBootstrap.Container.GetExportedValue<IMainViewModel>();
        }
    }

    private bool IsInDesignMode()
    {
        return DesignerProperties.GetIsInDesignMode(dummy);
    }
}
And on App.xaml file you could include as a resource. Define the namespace on the class above and register it on the resources.
xmlns:core="clr-namespace:YourNameSpace"
 
<Application.Resources>
    <core:ViewModelLocator x:Key="ViewModelLocator" />
</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:
<Window x:Class="WpfGuide.Views.MainView"
        ...
        DataContext="{Binding Path=MainViewModel,
            Source={StaticResource ViewModelLocator}}"
        >
With the example above I will have a mock viewmodel while I’m designing the application:
01
And real values when I’m running it:
02
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