开发者

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

开发者 https://www.devze.com 2023-02-02 02:44 出处:网络
In the StockTraderRI sample code the ViewModel is injected by MEF using a property: [Export(typeof(IOrdersView))]

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 IOrdersVi开发者_运维技巧ewModel 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消