Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Style Inheritance Inside ItemsControl / DataTemplate in WPF?

Tags:

c#

wpf

xaml

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>
like image 950
maxp Avatar asked Dec 01 '16 09:12

maxp


1 Answers

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.

like image 76
Vishnu Babu Avatar answered Nov 05 '22 01:11

Vishnu Babu