Question

I have a DataTemplate inside a global/shared ResourceDictionary like this which targets a DataType:

<DataTemplate DataType="{x:Type foo:Bar}">
    <!-- My DataTemplate visual tree goes here... -->
</DataTemplate>

This DataTemplate replaces my all foo:Bar types on all my Views (UserControls/Windows). What I want to do is to apply this template to only certain views, keeping the other views are not affected by this DataTemplate. I can copy this DataTemplate to Resources sections of each of these view, but I don't want to copy/paste the contents of the DataTemplate which would result in maintenance headaches.

Was it helpful?

Solution

What you are using here is called implicit data template. And you are asking for an explicit one. To accomplish this you could use explicit resource key:

<DataTemplate x:Key="MyStyle" DataType="{x:Type foo:Bar}">
    <!-- My DataTemplate visual tree goes here... -->
</DataTemplate>

And later in xaml:

<ContentPresenter ContentTemplate="{StaticResource MyStyle}" .../>

Another solution would be one resource dictionary (with implicit data templates) used via Merged Dictiories inside appropriate Control/Page.

I prefer the first approach, because it's easier to maintain (implicit styles are way harder to trace).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top