简体   繁体   中英

Silverlight MEF - importing resources and putting into generic.xmal

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)

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

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))
    {

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM