如何从MEF组件提供XAML资源

如何从MEF组件提供XAML资源

本文介绍了如何从MEF组件提供XAML资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个导入MEF组件,该组件会在导入向导打开时动态加载.一旦用户选择了要处理的导入类型,对导入向导对话框的控制就会传递给所选的导入组件.当然,导入组件需要向向导对话框提供资源(例如,DataTemplate).目前,这是通过导入组件提供的DataTemplateSelector实现的.他们访问导入组件的程序集的本地ResourceDictionary.

I have an import MEF component which is dynamically loaded when the import wizard opens. As soon as the user selects the type of import she wants to process, the control over the import wizard dialog is passed to the chosen import component.Of course, import components need to supply resources to the wizard dialog (e. g. DataTemplates). At the moment this is implemented via DataTemplateSelectors which are provided by the import components. They access a local ResourceDictionary of the import component's assembly.

但是,您可以想象,这很繁琐:我必须为每个要提供的DataTemplate添加代码,WPF不会根据显示的ViewModel的类型自动使用正确的DataTemplate.

But as you can imagine, this is tedious: I have to add code for every DataTemplate to provide, WPF does not automatically use the right DataTemplate by the type of the ViewModel being displayed.

有人以前解决过这个问题吗?你们在那里如何在插件环境中提供资源?

Has anybody solved this problem before? How do you guys out there provide resources in a plug-in environment?

谢谢您的帮助.

最诚挚的问候

推荐答案

我不知道在哪里找到这个小技巧,但是您可以做的一件事就是在编写外部程序集时动态导入资源字典.

I lost track of where I found this little trick, but one thing you can do is dynamically import resource dictionaries when you compose external assemblies.

在每个具有资源的程序集中,您都可以通过在后面添加代码并进行如下注释来导出一个或多个ResourceDictionary对象:

In each assembly with resources, you export one or more ResourceDictionary objects by going code behind and annotating like this:

[Export(typeof(ResourceDictionary))]
public partial class Resources : ResourceDictionary
{
    public Resources()
    {
        InitializeComponent();
    }
}

现在,您需要一个可解析[ImportMany] IEnumerable<ResourceDictionary> resourceDictionaries并执行以下操作的组件:

Now you need a component that resolves an [ImportMany] IEnumerable<ResourceDictionary> resourceDictionaries and do something like this:

        //Merge exported resource dictionaries from all composed sources into the application
        foreach (var resourceDictionary in resourceDictionaries)
        {
            Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
        }

这篇关于如何从MEF组件提供XAML资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:01