WPF Some styles not applied on DataTemplate controls

I discovered a simple workaround for this. For any elements that are not able to search outside the data template encapsulation boundary (i.e. are not being implicitly styled), you can just declare an empty style within the data template for that element type and use the BasedOn attribute of the style to find the correct implicit style outside the data template to apply.

In the example below, the TextBox is able to search outside the data template encapsulation boundary (because it inherits from Control?), but the TextBlock is not able to, so I declare the empty style for it which can search outside the data template.

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <DataTemplate.Resources>
            <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}" />
        </DataTemplate.Resources>
        <DockPanel>
            <TextBlock Text="{Binding Name}"  />
            <TextBox Text="{Binding Value}" />
        </DockPanel>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Leave a Comment