Wpf – DataTemplates in resource dictionaries don’t inherit from app.xaml styles

app.xamlresourcedictionarystyleswpf

I added custom named styles to the app.xaml.

I created an external resource dictionary (which I attach in the merged dictionaries of the app.xaml) and when I try to use one of the above named styles in the rcource dictionary, it says that there is no such style.

Also the default styles (i.e. unnamed styles that apply for the entire application) don't apply on the template elements.

Note: The Build Action of the templates is 'Page'.


Here is an example of how my code is written:

<Application x:Class="Application"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
    ShutdownMode="OnExplicitShutdown">
    <Application.Resources>
        <ResourceDictionary>

            <Style
                    x:Key="StackPanelStyle" 
                    TargetType="StackPanel" 
                    BasedOn="{StaticResource {x:Type StackPanel}}">
                <Setter Property="Margin" Value="5"/>
                <Setter Property="Orientation" Value="Horizontal" />
                <Setter Property="Height" Value="40"/>
            </Style>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Templates/DataTemplate1.xaml"/>
                <ResourceDictionary Source="/Templates/DataTemplate2.xaml"/>
                <ResourceDictionary Source="/Templates/DataTemplate3.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

This an example of the data template:

<DataTemplate DataType="{x:Type Entity}" x:Key="NameDataTemplate">
    <Expander>
        <StackPanel>
            <--The following line produces: StackPanelStyle was not found.-->
            <StackPanel Style="{StaticResource StackPanelStyle}">
                <Label Content="Name:"/>
                <TextBox Text="{Binding Name}"/>
            </StackPanel>
        </StackPanel>
    </Expander>
</DataTemplate>

Any ideas?
Do I have to merge the dictionaries in a different way?

Best Answer

The code won't work well because the DataTemplate in the resource dictionary doesn't know which one is using it, it just been used. Like Hollywood mode. They compiled separately.

To make this work, you can put your style which in app.xaml in the same resource dictionary of the DataTemplate or if you don't like this coupling, you can put it in a different resource dictionary, and merge it into the DataTemplate's resource dictionary.

Related Topic