Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP Why does a style not apply to TargetTypes in DataTemplate?

Tags:

xaml

uwp

Given a style in a Page.Resource:

    <Style x:Name="ItemTitle" TargetType="TextBlock">
        <Setter Property="FontSize" Value="16"></Setter>
        <Setter Property="FontWeight" Value="Bold"></Setter>
    </Style>

It is correctly applied to any regular TextBlock on the same page.

However, when I use a DataTemplate for an Item in a GridView on that page, this style does not apply.

    <DataTemplate  x:Key="Output" x:DataType="vm:Output">
        <TextBlock Text="{x:Bind Text}"></TextBlock>
    </DataTemplate>

It does work when I apply the style explicitly on the DataTemplate, e.g.:

    <DataTemplate  x:Key="Output" x:DataType="vm:Output">
        <TextBlock Style="{StaticResource ItemTitle}" Text="{x:Bind Text}"></TextBlock>
    </DataTemplate>

Does anyone know what's up?

like image 717
Arwin Avatar asked Nov 23 '25 07:11

Arwin


1 Answers

It's expected and intentional. If it doesn't derive from Control (like DataTemplate) then it won't inherit an implicit style unless they're in the application resource dictionaries as global defaults.

Or more specifically;

Templates are viewed as an encapsulation boundary when looking up an implicit style for an element which is not a subtype of Control.

Hope this helps. Cheers.

Addendum:

If it's a situation where you have a lot of the same element nested in a Template you can just set it once and allow it to inherit to all the nested controls of the type like (in pseudo);

<Parent>
  <Parent.Resources>
    <Style TargetType="TextBlock" BasedOn="{StaticResource ItemTitle}"/>
  <Parent.Resources>

  <!-- These will all inherit the Style resource now,
       without explicit style setting individually. -->
  <TextBlock/>
  <TextBlock/>
  <TextBlock/>

</Parent>
like image 132
Chris W. Avatar answered Nov 24 '25 23:11

Chris W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!