如何在Prism中使用DataTemplates

Tho*_*enz 5 wpf dependency-injection prism datatemplate

我一直在使用Prism一段时间,并享受解耦我的模块更容易.

这对视图和视图模型特别有用,因为您可以通过接口注入视图模型,并通过区域管理器注入视图.

不幸的是,这只适用于我的观点是完全成熟的用户控件,除非我在这里遗漏了一些东西(我真诚地希望我是).

很多时候,我会创建一个ViewModel和一个匹配的DataTemplate.然后,其他程序集可以使用它们来组成视图.

我的问题是,在没有引用包含程序集的情况下,我看不到引用这些datatemplates的方法,所以在我的xaml文件中我写了类似的东西:

<ResourceDictionary Source="pack://application:,,/......>
Run Code Online (Sandbox Code Playgroud)

当然,这并没有真正解耦,虽然我试图确保,我没有在我的代码中的任何其他地方引用程序集.

我想到的另一个解决方案是将datatemplates放入Infrastructure项目中,但我也不太喜欢,因为我希望包含属于模块的所有东西(当然除了接口).

那么,有没有人有一个很好的解决方法,或者我是否错过了一些Prism功能?

Dan*_*att 4

我建议创建一个服务,将资源字典添加到 Application.Resources.MergedDictionaries 集合中。

// Service interface (defined in the 'infrastructure' project)
public interface IResourceAggregator
{
    void AddResource(Uri resourceUri);
}

// Service implementation (implemented at the application/shell level)
class ResourceAggregator : IResourceAggregator
{
    public void AddResource(Uri resourceUri)
    {
        var resourceDictionary = new ResourceDictionary() { Source = resourceUri };
        var app = Application.Current;
        app.Resources.MergedDictionaries.Add(resourceDictionary);
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望您在模块加载期间“解析”此服务并使用它来“注册”模块本地资源字典。