First experiments using MEF, MVVM and Silverlight 4 Beta

Note – this is a multi part post:

MEF (Managed Extensibility Framework) is a new library available in Silverlight 4 Beta which permits to build applications that can be incrementally extended in a declarative way using three simple concepts (read this post by Glenn Block for more infos):

  • Export an object;
  • Import it;
  • Compose it.

Mixing MEF and commanding, Silverlight has now a great support for structuring projects using a ViewModel approach, so I decided to use these new characteristics to build a simple solution.

Given an existing project, I added a ViewModel class implementing INotifyPropertyChanged:

    [Export("MainPageViewModel"))]
    public class MainPageViewModel : ViewModelBase
    {
        public MainPageViewModel()
        {
            aViewModelProperty = "This is the content of a ViewModel property";

            aSampleCommand = new AViewCommand();
        }

        public string aViewModelProperty { get; set; }

        public ICommand aSampleCommand {get; set;}
    }

The problem I’ve solved using MEF is the binding of the DataContext property of the UserControl to a ViewModel class instance, so I’ve exported it using the MEF [Export] attribute.

The [Import] attribute and the PartInitializer.SatisfyImports(this);  are then used in the code behind of the xaml view in order to import and compose the ViewModel instance with the DataContext:

        public MainPage()
        {
            InitializeComponent();

            PartInitializer.SatisfyImports(this);
            this.DataContext = mainPageViewModel;
        }

        [Import("MainPageViewModel")]
        public object mainPageViewModel { get; set; }

And this is the result:

MEFMVVM

As usually the source code is available for download here.

Happy Silverlighting!