This project has moved and is read-only. For the latest updates, please go here.

How to inject ViewModel using MEF

Apr 4, 2012 at 4:17 AM

The Stocktrader RIA demo injects ViewModel through property rather than through the View constructor as shown below:

using System.ComponentModel.Composition;
using System.Windows.Controls;
using StockTraderRI.Infrastructure;

namespace StockTraderRI.Modules.Position.PositionSummary
    [ViewExport(RegionName = RegionNames.MainRegion)]
    public partial class PositionSummaryView : UserControl
        public PositionSummaryView()

        #region IPositionSummaryView Members

        public IPositionSummaryViewModel Model
                return DataContext as IPositionSummaryViewModel;
                DataContext = value;

My questions are the following: 
What triggers the assignment of the DataContext property? How is the ViewModel being injected via the Model property?
How is the ViewModel being instantiated in this example ?
Thank you for your help.
Apr 5, 2012 at 9:04 AM

The assignment of DataContext cause the {Binding} markup extensions to use this specific object instance.

Please read this link for more details.


The ViewModel is instantiated by MEF, that's the thing it does. Look for class that both implment IPositionSummaryViewModel and has [Export(typeof(IPositionViewModel))] on it.