Sam
Sam

Reputation: 28999

Prism/mef ViewModel: pro and con of property against ctor

In the StockTraderRI sample code the ViewModel is injected by MEF using a property:

[Export(typeof(IOrdersView))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class OrdersView : UserControl, IOrdersView
{
  public OrdersView()
  {
    InitializeComponent();
  }

  [Import]
  [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly", Justification = "Needs to be a property to be composed by MEF")]
  public IOrdersViewModel ViewModel
  {
    set { this.DataContext = value; }
  }
}

What I wonder is: why not use an ImportingConstructor like this to inject the ViewModel:

[Export(typeof(IOrdersView))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class OrdersView : UserControl, IOrdersView
{
  [ImportingConstructor]
  public OrdersView(IOrdersViewModel ViewModel)
  {
    InitializeComponent();
    this.DataContext = ViewModel;
  }
}

Is there a special feature, problem or reason I miss why the StockTraderRI sample does use a Property instead of a paramter to the ctor?

Upvotes: 2

Views: 702

Answers (1)

Jon
Jon

Reputation: 437336

Because types partially defined in XAML don't play well with parametrized constructors. XAML is built on the "create a blank object and fill in the properties afterwards" paradigm.

Upvotes: 5

Related Questions