【发布时间】:2016-04-18 12:31:56
【问题描述】:
我整天都在寻找这个问题的答案,但没有提出任何直接适用于我的案例的解决方案,或者任何可行的解决方案(在我发现的一个案例中是适用的)。
我设置了一个使用 MEF 的 Caliburn.Micro 框架,并且可以很好地加载我的模块化元素。缺少的一件事是让 WPF 识别我在其中一个模块中使用的资源。
如何在我的应用引导程序中加载模块
[ImportMany]
private IEnumerable<IMyModule> _myModules;
protected override void Configure()
{
// Because Configure() is also called from SelectAssemblies(), we cannot instantiate MEF again because it will create conflicts.
if (_configured)
{
return;
}
AggregateCatalog aggregateCatalog = new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());
aggregateCatalog.Catalogs.Add(new DirectoryCatalog(ConfigurationManager.AppSettings["MyModuleFolderLocation"]));
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));
_container = new CompositionContainer(aggregateCatalog);
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue<IWindowManager>(new WindowManager());
batch.AddExportedValue<IEventAggregator>(new EventAggregator());
batch.AddExportedValue(_container);
_container.Compose(batch);
_container.SatisfyImportsOnce(this);
_configured = true;
}
protected override IEnumerable<Assembly> SelectAssemblies()
{
// SelectAssemblies() is called before Configure(), so manually force Configure() to run first so that MEF is instantiated properly
Configure();
if (!_configured)
{
throw new Exception("Unable to configure assemblies");
}
List<Assembly> assemblies = new List<Assembly>();
assemblies.Add(Assembly.GetExecutingAssembly());
// Need to add all module assemblies so that Caliburn will be able to find the View for a ViewModel
foreach(IMyModule myModule in _myModules)
{
Assembly assembly = myModule.GetType().Assembly;
assemblies.Add(assembly);
}
return assemblies.Distinct();
}
这可以很好地让模块正确显示。
但是当一个模块使用了一个图像时,这个图像永远不会显示,因为这种加载显然没有考虑资源。 我在模块项目中创建了一个 Resources.resx 文件并向其中添加了一个图像。然后,Visual Studio 中显示的图像文件有一个生成操作,上面写着“资源”和“不要复制(到输出目录)”。这应该意味着图像嵌入在生成的 DLL 文件中。
图像被放置在模块项目中名为“Resources”的文件夹中,XAML 像这样使用它:
<Image Source="/Resources/myImage.png" />
图像在 Visual Studio 的预览中显示,但在应用程序运行时不显示。
我尝试过的方法不起作用
- 以另一种方式引用图像:
<Image Source="pack://application:,,,/Resources/myImage.png" /> - 以 BAML 形式获取资源并将它们重新插入到正在执行的程序集中,例如以下问题:Instantiate ResourceDictionary xaml from other Assembly(这会导致此行出现 OutOfMemoryException
var reader = new Baml2006Reader(stream);) - 很多其他答案都引用了 ResourceDictionary,但我有一个 Resource.resx 文件(它只生成一个不是 ResourceDictionary 的内部类)
问题依然存在
如何让 WPF/Caliburn.Micro 识别 MEF 加载的 DLL 中的资源?
【问题讨论】:
-
该问题涉及嵌入在 XAML 文件中的 ResourceDictionaries。正如我指定的,我没有 ResourceDictionaries,而是一个 RESX 文件。
-
在哪里将
DictionaryEntry插入主应用程序? -
哎呀,
DictionaryEntry是什么意思? -
您链接到的问题具有以下代码:
foreach (DictionaryEntry entry in reader)这很好,因为我认为它包含我的 RESX 文件中的内容。但是,一旦我得到了DictionaryEntry,我该怎么办?我相信我应该把它放在某个地方(比如Application.Current.Resources),但我找不到任何接受DictionaryEntry作为输入的东西。
标签: c# wpf xaml mef caliburn.micro