Last Updated: February 25, 2016
·
1.911K
· brendanjcaffrey

MVVM Light & MEF Quick Start Guide

I just wanted to lay out a quick start guide for turning a new project into one that uses MEF/MVVM Light.

  • Install MVVM Light via NuGet.
  • Add a DataContext to all your views in the Window XAML element: (Path=Main should be the name of the property in ViewModelLocator):
<Window DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
  • Add the MEF references to your project: right click on References under your project, click Add Reference... and select everything under System.ComponentModel.
  • Add an [Export] tag on all your view models:
[Export]
public class MainViewModel : ViewModelBase
{
    // ...
}
  • In your ViewModelLocator constructor, build a CompositionContainer and get your view models by exporting them from that:
public class ViewModelLocator
{
    private CompositionContainer container;

    public ViewModelLocator()
    {
        var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        this.container = new CompositionContainer(catalog);
    }

    public MainViewModel Main
    {
        get
        {
            return this.container.GetExportedValue<MainViewModel>();
        }
    }
}