Tag Archives: MVVM

Use MEF to load ViewModel in Silverlight 4

24 May

It has become increasingly popular to use the Model-View-ViewModel (MVVM) in Silverlight. It’s easy to use the MVVM in Silverlight and it opens up for some extended testing scenarios. With Silverlight 4 we can also use some of the features from MEF (Managed Extensibility Framework). One scenario is to use MEF to load the ViewModel to a View.

How to do it

For this demo I have created a Silverlight project with a view called CustomerView.xaml and a viewmodel called CustomerViewModel.cs. The view contains an ItemsControl with an ItemTemplate that I will use to display a list of Customers and their address. I have bound the ItemsSource to the Customers property from my viewmodel.


In the code-behind of the MainPage.xaml file hosting the view, I have created a property called ViewModel. When the ViewModel property is set it will set the DataContext of our view to the provided value. I have added an Import attribute to the ViewModel. The Import attribute declare that this property relies on a service provided by some other component.


I have added an Export attribute to the CustomerViewModel class. The Export attribute declares that this class provides a particular kind of service.


To connect the components together I need to resolve the Imports and Exports. It is done by a class called CompositionContainer. In most cases you will just call CompositionInitializer.SatisfyImports method to try and provide components that export all the things you need to import.


You can write your own CompositionContainer explicitly if you want.

My viewmodel will now be resolved and an instance will be set the DataContext of the view.

The consequenses

This is a very simplified sample and can seem a bit like shooting birds with cannons. In larger scale you will really see the power of using this solution where your views do not need to know about its viewmodel.

This solution will let you use an other viewmodel in designtime supporting the use of using a viewmodel and Expression Blend.

On the other hand this solution will add some complexity to the project. It will be harder to follow the code and it is often not clear from looking at the code what sorts of objects you’re really using or how they were instantiated.

Sample code

Get the sample code here: http://bit.ly/bxZ1Ly

by xamlgeek