【问题标题】:How to load WPF treeview resources from another assembly using MEF?如何使用 MEF 从另一个程序集加载 WPF 树视图资源?
【发布时间】:2015-11-20 17:38:05
【问题描述】:

我正在创建一个使用 MEF 加载其插件的 WPF 应用程序。 如何包含来自我正在使用 MEF 加载的另一个程序集的资源? 具体来说,我想在外部程序集中创建一个 HierarchicalDataTemplate 并在启动时编写应用程序时将其动态加载到 Treeview.Resources 中。 这样的事情可能吗?

如果重要的话,我正在使用 Caliburn.Micro,但我确信这个问题适用于一般的 WPF 应用程序。

【问题讨论】:

    标签: wpf xaml caliburn.micro resourcedictionary


    【解决方案1】:

    这就是我最后的做法。
    因为如果您使用 MEF 的 DirectoryCatalog 加载程序集,Caliburn.Micro 无法正常工作,我必须手动执行。 Bellow 是执行此操作并加载包含在单独 resources.xaml 文件中的 ResourceDictionary 的代码的简化部分。

    FileInfo[] filesInfo = new DirectoryInfo(pluginPath).GetFiles("*.dll");
    AssemblySource.Instance.AddRange(filesInfo.Select(fileInfo => Assembly.LoadFrom(fileInfo.FullName)));
    
    // load resources from plugins
    var dictionaries = App.Current.Resources.MergedDictionaries;
    dictionaries.Clear();
    
    foreach (FileInfo fileInfo in filesInfo)
    {
        string assemblyName = Path.GetFileNameWithoutExtension(fileInfo.Name);
        string uriString = assemblyName + @";component/resources.xaml";
    
        try
        {
            dictionaries.Add(new ResourceDictionary { Source = new Uri(uriString, UriKind.Relative) });
        }
        catch
        {
            // do some logging
        }
    

    【讨论】:

      【解决方案2】:

      如果您尝试加载静态资源,您应该在加载主窗口之前加载资源。 如果您尝试加载动态资源,则应在加载使用该资源的视图之前加载该资源。

      您应该通过在引导时将资源添加到 Wpf 应用程序合并字典来添加对资源的引用。

      //On the bootstrapper add the following code
       ResourceDictionary rd = new ResourceDictionary
                                      {
                                          Source =
                                              new Uri(
                                                  "pack://application:,,,/DllName;component/Themes/ResourceName.xaml",
                                                  UriKind.RelativeOrAbsolute)
                                      };
      
      
      Application.Current.Resources.MergedDictionaries.Add(rd);
      

      【讨论】:

      • 谢谢伊莱。但是如何在我的主视图中告诉我的 TreeView 使用我加载的 HierarchicalDataTemplate?
      • 在加载的程序集中用你的 HierarchicalDataTemplate 定义一个资源字典。模板不应仅具有键 DataType。例如: 加载应用程序时,它将在本地搜索模板并最终在应用程序资源中搜索。
      • 再次感谢。你把我引向了正确的方向。
      猜你喜欢
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多