【问题标题】:Create instance from attribute从属性创建实例
【发布时间】:2012-01-16 04:30:23
【问题描述】:

我在 WPF 应用程序中使用 MVVM viewmodel-first 模式,我有一些如下定义:

public interface IMyView { }

[Export(typeof(IMyView))]
public class MyView : UserControl, IMyView { }

[ViewTypeAttribute(typeof(IMyView))]
public interface IMyViewModel { }

[Export(typeof(IMyViewModel))]
public class MyViewModel : ViewModelBase, IMyViewModel { }

ViewTypeAttribute 是一个自定义属性,用于检索应将哪个View 用作给定DataTemplateDataTemplate。真的在这里我有一个Type!但我不知道如何通过MEFType 创建一个实例?有人可以帮帮我吗?

【问题讨论】:

    标签: c# wpf c#-4.0 mvvm mef


    【解决方案1】:

    使用:

    var container = new CompositionContainer(/* your container .ctor here */);
    var type = typeof (IYourType); // read the type from attribute
    var export = container.GetExports(type, null, null).FirstOrDefault();
    var obj = export.Value as YourCostingHere;
    

    【讨论】:

      【解决方案2】:

      为什么你不使用内置的 wpf 东西来为你的视图模型获得正确的视图?如果您只是为您的视图模型创建一个数据模板并设置正确的视图/用户控件。然后一切都完成了。

      <DataTemplate DataType={vm:IMyViewModel}>
        <local:MyIViewUserControl />
      </DataTemplate>
      

      应用程序中将视图模型绑定到内容控件的任何位置,内容控件呈现为 MyIViewUserControl。

      编辑:也许我错了,但我认为您使用 ViewTypeAttribute(MEF 导出属性)来获取视图和视图模型之间的链接。然后你想用这些信息创建一个数据模板吗?

      那么为什么不直接导出 DataTemplate 并将其添加到 app.resources 中呢?

      【讨论】:

      • 因为我的设计要求!!!您的A 不是我问题的答案!请再读一遍
      猜你喜欢
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多