【问题标题】:Silverlight MEF - importing resources and putting into generic.xmalSilverlight MEF - 导入资源并放入 generic.xaml
【发布时间】:2012-01-22 12:48:53
【问题描述】:

我有一个带有 generic.xaml 文件的 silverlight 应用程序。 在通用文件中,我想合并 MEF 从其他 DLL 导入的字典。

我该怎么做? (举个例子就好了)

【问题讨论】:

    标签: silverlight mef generic.xaml


    【解决方案1】:

    我在加载一个特定模块时执行此操作,并且效果很好。

    在模块的构造函数中,添加对将加载资源的方法的调用 - 这很有效,因为通过这样做,我会收到缺少资源的异常通知:

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

    【讨论】:

      【解决方案2】:

      我使用以下:

      使用 mef 导出我的资源字典(只需将 .cs 文件添加到您的资源字典)

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

      将新的类文件添加到您的 xaml

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

      在你想要的地方导入资源,例如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
      

      至少这里是导出属性

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

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 1970-01-01
        • 2011-05-19
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        相关资源
        最近更新 更多