创建实例从属性

问题描述:

我使用MVVM视图模型一模式在WPF应用程序,我有这样的一些定义:创建实例从属性

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对于给定的ViewModel应该用作DataTemplate。真的在这里我有一个Type!但我不知道如何通过MEFType创建实例?有人可以帮助我吗?

使用:

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; 

为什么你不使用内置的wpf东西来为你的viewmodel获得正确的视图?如果你只是为你的viewmodel创建一个datatemmplate并设置正确的view/usercontrol。然后全部完成。

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

任何地方在您的应用程序,你您的视图模型绑定到ContentControl中其呈现为MyIViewUserControl。

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

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

+0

因为我的设计要求!你的'A'不是我的问题的答案!请再读一遍 – 2012-01-16 18:27:47

+0

看我的编辑请。我想念什么? – blindmeis 2012-01-17 06:33:11