0
votes

I am trying to think of Xamarin (XAML) styles like CSS and finding it to not be quite the same. For example, if I want all labels to be white but certain labels to also be bold, logically I would think this would work.

    <ResourceDictionary>
        <Style TargetType="Label">
            <Setter Property="TextColor" Value="White" />
        </Style>
        <Style x:Key="LargeLabel" TargetType="Label">
            <Setter Property="FontAttributes" Value="Bold" />
        </Style>
    </ResourceDictionary>

and in the page...

    <Label Text="Good Morning David!" Style="{StaticResource LargeLabel}" />

However, that gives me a bolded black label. I would expect it to be white instead.

So after some research it was suggested the BasedOn attribute can be of help. The technique is to create an explicit style that the implicit style bases itself on. So that makes all Labels white. And then further explicit styles can be BasedOn the same parent.

    <ResourceDictionary>
        <Style TargetType="Label" x:Key="DefaultLabelStyle">
            <Setter Property="TextColor" Value="White" />
        </Style>
        <Style x:Key="LargeLabel" TargetType="Label" BasedOn="DefaultLabelStyle">
            <Setter Property="FontAttributes" Value="Bold" />
        </Style>
        <Style TargetType="Label" BasedOn="DefaultLabelStyle" />
    </ResourceDictionary>

and in the page the same thing...

    <Label Text="Good Morning David!" Style="{StaticResource LargeLabel}" />

However, that still results in bolded black label instead of a bolded white label.

Is there a way to make this work in XAML/Xamarin Forms?

1

1 Answers

2
votes

BasedOn must be a StaticResource per Xamarin Documentation

This is how I would do it in my projects:

<ResourceDictionary>
    <Style TargetType="Label" x:Key="DefaultLabelStyle">
        <Setter Property="TextColor" Value="White" />
    </Style>
    <Style x:Key="LargeLabel" TargetType="Label" BasedOn="{StaticResource DefaultLabelStyle}>
        <Setter Property="FontAttributes" Value="Bold" />
    </Style>
</ResourceDictionary>

My working source code example