Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide XAML resources from MEF components

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.

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?

Thank you for any help in advance.

Best regards

like image 948
oddparity Avatar asked May 10 '12 08:05

oddparity


People also ask

How do I add resources to XAML dictionary?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1.

What is static resource in XAML?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

What default resources are supported in WPF?

WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.


1 Answers

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.

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();
    }
}

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);
        }
like image 59
Dan Bryant Avatar answered Sep 20 '22 22:09

Dan Bryant