How to inject ViewModel using MEF

Apr 4, 2012 at 3: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)]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public partial class PositionSummaryView : UserControl
    {
        public PositionSummaryView()
        {
            InitializeComponent();
        }

        #region IPositionSummaryView Members

        [Import]
        public IPositionSummaryViewModel Model
        {
            get
            {
                return DataContext as IPositionSummaryViewModel;
            }
            set
            {
                DataContext = value;
            }
        }
        #endregion
    }
}


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 8: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.

 

Ido.