开发者

How to use DataTemplates in Prism

开发者 https://www.devze.com 2022-12-19 17:46 出处:网络
I have been using Prism for a while now and enjoy how much easier it is to decouple my mod开发者_StackOverflowules.

I have been using Prism for a while now and enjoy how much easier it is to decouple my mod开发者_StackOverflowules.

This works especially great for views and view models since you can inject the view models via interfaces and the views via the region manager.

Unfortunately this only works when my views are full blown user controls unless I'm missing something here (and I sincerely hope I am).

A lot of times though, I'll create a ViewModel and a matching DataTemplate. These can then be used by other assemblies to compose a view.

My problem is, that I see no way of referring to these datatemplates without referencing the containing assembly, so in my xaml file I write something like:

<ResourceDictionary Source="pack://application:,,/......>

Of course this is not really decoupled, although I try to make sure, that I don't refer to the assembly anywhere else in my code.

Another solution I thought of, was to put the datatemplates into the Infrastructure project, but I don't like that too much either,as I want everything that belongs to a module to be contained in it (except the interfaces of course).

So, does anyone have a good workaround, or did I miss some Prism feature?


I would suggest creating a service that encapsulates adding resource dictionaries to the Application.Resources.MergedDictionaries collection.

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

I would expect you would "resolve" this service during module load and use it to "register" the module-local resource dictionaries.


You would need to merge the resources when the module starts. You can read more about this here: http://blogs.southworks.net/jdominguez/2008/09/presentation-model-with-datatemplates-in-compositewpf-prism-sample/

Of course you can further abstract this functionality into a reusable service.

0

精彩评论

暂无评论...
验证码 换一张
取 消