【问题标题】:Using MEF to import a WPF DataTemplate?使用 MEF 导入 WPF DataTemplate?
【发布时间】:2009-05-09 03:01:13
【问题描述】:

我曾将 MEF 视为一个可扩展性框架,但我非常喜欢,除了一点:

假设我想同时导入一个 ViewModel 和一个 View 来显示它。我认为“正确”的做法是让 MEF 部分导出 ViewModel 类和显示 ViewModel 的 DataTemplate。例如,假设您正在构建一个类似 Visio 的应用程序,并且您想要导入一个形状库。每个形状都需要一个在 Xaml 中定义的 View 和一个包装一些底层 Model 对象的 ViewModel。

这可能吗? DataTemplate 的 Import 合同是什么样的?如何让 WPF 知道导入的 DataTemplate?

【问题讨论】:

    标签: wpf mvvm datatemplate mef


    【解决方案1】:

    是的,我能够通过以下方式完成这项工作:

    在我的主机 WPF 应用程序中,我添加了这个 Import:

        [ImportMany("ApplicationResources", typeof(ResourceDictionary))]
        public IEnumerable<ResourceDictionary> Views { get; set; }
    

    然后在我的复合部分中,我在常规 ResourceDictionary Xaml 文件中声明了一个 ViewModel 和一个 ViewModel 的数据模板。然后我为 ResourceDictionary 创建了一个代码,如下所示(在此示例中,ViewModel 称为 ItemViewModel,ResourceDictionary 称为 ItemView):

    [Export("ApplicationResources", typeof(ResourceDictionary))]
    public partial class ItemView : ResourceDictionary 
    {
        public ItemView()
        {
            InitializeComponent();
        }
    }
    

    作为参考,示例 ResourceDictionary 的 Xaml 如下所示:

    <ResourceDictionary 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyCompany.MyProduct"
        x:Class="MyCompany.MyProduct.ItemView">
    
        <DataTemplate DataType="{x:Type local:ItemViewModel}">
            ...
        </DataTemplate>
    
    </ResourceDictionary>
    

    然后,回到我的主机 WPF 应用程序,在我成功撰写之后,在我显示主窗口之前,我这样做:

    // Add the imported resource dictionaries
    // to the application resources
    foreach (ResourceDictionary r in Views)
    {
        this.Resources.MergedDictionaries.Add(r);
    }
    

    这似乎成功地在 WPF 看到 ItemViewModel 的任何地方应用 DataTemplate。

    编辑:对于任何感兴趣的人,我发布了一个名为SoapBox Core 的开源应用程序框架,它广泛使用这种方法将视图导入应用程序资源。效果很好,你可以自己下载源码看看效果如何。

    【讨论】:

    • 我尝试了这种确切的方法,但 ResourceDictionary 在加载时为空。有没有办法强制初始化或者我做错了什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多