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 theWindow
XAML element: (Path=Main
should be the name of the property inViewModelLocator
):
<Window DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
- Add the MEF references to your project: right click on
References
under your project, clickAdd Reference...
and select everything underSystem.ComponentModel
. - Add an
[Export]
tag on all your view models:
[Export]
public class MainViewModel : ViewModelBase
{
// ...
}
- In your
ViewModelLocator
constructor, build aCompositionContainer
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>();
}
}
}
Written by Brendan Caffrey
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Csharp
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#