Silverlight MEF - importing resources and putting into generic.xmal

433 views Asked by At

I have a silverlight application with generic.xaml file. In the generic file I would like to merge dictionaries that are imported by MEF from other DLLs.

How can I do that ? (an example would be nice)

2

There are 2 answers

0
bperreault On

I do this when one specific module loads, and it works well.

In the constructor of the module, add a call to the method that will load the resources - this works well because by doing it this way, I will be informed by exceptions of missing resources:

 addResourceDictionaries();



 protected void addResourceDictionaries()
    {
        LoadResource ( new Uri("/NAME_OF_DLL;component/assets/name_and_path_of_xaml.xaml", UriKind.Relative));
    }

private void LoadResource(Uri uri)
    {
        var info = System.Windows.Application.GetResourceStream(uri);
        string xaml;
        using (var reader = new System.IO.StreamReader(info.Stream))
        {
            xaml = reader.ReadToEnd();
        }

        ResourceDictionary result = System.Windows.Markup.XamlReader.Load(xaml) as ResourceDictionary;

        if (result != null)
        {
            System.Windows.Application.Current.Resources.MergedDictionaries.Add(result);
        }
    }
0
blindmeis On

i use the following:

export my resourcedictionary with mef (simply add a .cs file to your Resourcedictionary)

[ExportResourceDictionary]
public partial class MyResourcen : ResourceDictionary
{
    public MyResourcen()
    {
        InitializeComponent();
    }
}

add the new class file to your xaml

<ResourceDictionary x:Class="Test.Resourcen.MyResourcen">

import the resources where you want, eg app.xaml

[ImportMany("Resourcen", typeof(ResourceDictionary), AllowRecomposition = true)]
private IEnumerable<ResourceDictionary> ImportResourcen { get; set; }

    #region Implementation of IPartImportsSatisfiedNotification

    public void OnImportsSatisfied()
    {
        foreach (var dic in ImportResourcen)
        {
            this.Resources.MergedDictionaries.Add(dic);
        }
    }

    #endregion

at least here are the exportattribute

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportResourceDictionaryAttribute : ExportAttribute
{
    public ExportResourceDictionaryAttribute() : base("Resourcen", typeof(ResourceDictionary))
    {

    }
}