Prism/mef ViewModel:财产相对于 ctor 的优点和缺点

发布于 2024-10-10 03:13:26 字数 948 浏览 3 评论 0原文

在 StockTraderRI 示例代码中,MEF 使用属性注入 ViewModel:

[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; }
  }
}

我想知道的是: 为什么不使用像这样的 ImportingConstructor 来注入 ViewModel:

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

是否有特殊功能、问题或原因 我想念为什么 StockTraderRI 示例确实使用属性而不是 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

注定孤独终老 2024-10-17 03:13:26

因为在 XAML 中部分定义的类型不能很好地与参数化构造函数配合使用。 XAML 构建在“创建空白对象并随后填充属性”范例之上。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文