问题描述
鉴于我有一个 shell 应用程序和几个使用 Microsoft ComposteWPF (Prism v2) 的单独模块项目...
Given that I have a shell application and a couple of separate module projects using Microsoft CompoisteWPF (Prism v2)...
收到命令后,模块会创建一个新的 ViewModel 并通过区域管理器将其添加到区域中.
On receiving a command, a module creates a new ViewModel and adds it to a region through the region manager.
var viewModel = _container.Resolve<IMyViewModel>();
_regionManager.Regions[RegionNames.ShellMainRegion].Add(viewModel);
我想我可以在模块中创建一个资源字典并设置一个数据模板来显示加载的视图模型类型的视图(见下面的 xaml).但是当视图模型被添加到视图中时,我得到的只是打印出的视图模型命名空间.
I thought that I could then create a resource dictionary within the module and set up a data template to display a view for the view model type that was loaded (see below xaml). But when the view model is added to the view, all I get is the view models namespace printed out.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Modules.Module1.ViewModels"
xmlns:vw="clr-namespace:Modules.Module1.Views"
>
<DataTemplate DataType="{x:Type vm:MyViewModel}">
<vw:MyView />
</DataTemplate>
</ResourceDictionary>
我可以通过添加到 App.xaml 来让它工作
I can get it to work by adding to the App.xaml
<Application.Resources>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Module1;component/Module1Resources.xaml"/>
<ResourceDictionary Source="pack://application:,,,/Module2;component/Module2Resources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</Application.Resources>
这很好,但这意味着在创建新模块时,需要添加 App.xaml 文件.我正在寻找的是模块的一种方式,因为它们加载以动态添加到 Application.Resources.这可能吗?
Which is fine, but it means that as new modules are created, the App.xaml file needs to be added to. What I'm looking for is a way for modules, as they load to dynamically add to the the Application.Resources. Is this possible?
推荐答案
在各个模块的初始化中,可以添加到应用资源中:
Within the initialisation of each module, you can add to the application resources:
Application.Current.Resources.MergedDictionaries
.Add(new ResourceDictionary
{
Source = new Uri(
@"pack://application:,,,/MyApplication.Modules.Module1.Module1Init;component/Resources.xaml")
});
或者如果你遵循一个约定,每个模块都有一个名为Resources.xmal"的资源字典...
Or if you follow a convention of each module has a resource dictionary called "Resources.xmal"...
protected override IModuleCatalog GetModuleCatalog()
{
var catalog = new ModuleCatalog();
AddModules(catalog,
typeof (Module1),
typeof(Module2),
typeof(Module3),
typeof(Module4));
return catalog;
}
private static void AddModules(ModuleCatalog moduleCatalog,
params Type[] types)
{
types.ToList()
.ForEach(x =>
{
moduleCatalog.AddModule(x);
Application.Current.Resources.MergedDictionaries
.Add(new ResourceDictionary
{
Source = new Uri(string.Format(
@"pack://application:,,,/{0};component/{1}",
x.Assembly,
"Resources.xaml"))
});
});
}
这篇关于复合 WPF (Prism) 模块资源数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!