5

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>
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
maxp
  • 24,209
  • 39
  • 123
  • 201
  • Possible duplicate of [Why doesn't my TextBlock/TextBox apply values from a Base Style?](http://stackoverflow.com/questions/7597455/why-doesnt-my-textblock-textbox-apply-values-from-a-base-style) – ASh Dec 01 '16 at 09:33
  • 1
    I don't know why this happens, but if you give the style an x:Key and then apply it as static resource it will work. – adminSoftDK Dec 01 '16 at 09:48

1 Answers1

5

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.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Vishnu Babu
  • 1,183
  • 1
  • 13
  • 37