maxp maxp - 1 day ago 5
C# Question

No Style Inheritance Inside ItemsControl / DataTemplate in WPF?

can anyone explain why the

TextBlock
inside my
DataTemplate
does not apply the style defined in my
UserControl.Resources
element, but the second
TextBlock
('Test B') does?

I think it may have to do with a dependency property somewhere set to not inherit, but I can't be sure.

<UserControl.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Padding" Value="8 2" />
</Style>
</UserControl.Resources>
<StackPanel>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--Padding does not apply-->
<TextBlock>Test A</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!--Padding applies-->
<TextBlock>Test B</TextBlock>
</StackPanel>

Answer

Templates are considered as a boundary. Elements within the templates falls in this boundary range, and look up for the style with a matching target type ends within this range at runtime as a result the TextBlock outside will pickup the style and the one inside wont. like adminSoftDK said you should give the style an x:Key and then apply it as static resource it will work. Check this.

Comments