Xamarn.Forms Style or StyleClass?

Viewed 1361

I've been working an a Xamarin.Forms application and I noticed that I have two options for applying styles. I can create a Style with a "class" property and use it with an elements "StyleClass" property like so:

    <Style Class="GenericButton" TargetType="Button">
        <Setter Property="BackgroundColor" Value="Orange"/>
    </Style>

    <Button StyleClass="GenericButton" Command="{Binding LoginCommand}" Text="Login" />

Or, I can write a Style with "x:Key" and use it with the "Style" property set to a static resource:

    <Style x:Key="GenericBut" TargetType="Button">
        <Setter Property="BackgroundColor" Value="Azure"/>
    </Style>

<Button Style="{StaticResource GenericBut}" Command="{Binding LoginCommand}" Text="Login" />

Either one seems to work, but I don't know which to use in general, and I cannot find the proper documentation on their purposes. StyleClass is an IList and I believe it applies styles like CSS, which seems useful, but I'm wondering if there would be unforeseen consequences of using it all the time.

Thanks

1 Answers

Regular styles follow the standard, relatively inflexible WPF model.

A style class can be created by setting the Class property on a Style to a string that represents the class name. The advantage this offers, over defining an explicit style using the x:Key attribute, is that multiple style classes can be applied to a VisualElement.

Multiple styles can share the same class name, provided they target different types. This enables multiple style classes, that are identically named, to target different types.

Like below code:

<ContentPage.Resources>
    <Style Class="style1" TargetType="Button">
        <Setter Property="BackgroundColor" Value="AliceBlue" />
    </Style>
    <Style Class="style2" TargetType="Button">
        <Setter Property="TextColor" Value="Red" />
    </Style>
    <Style Class="style1" TargetType="Label">
        <Setter Property="TextColor" Value="Red" />
    </Style>
</ContentPage.Resources>

Multiple style classes can be applied to a control because the StyleClass property is of type IList.

 <Button
            x:Name="btn1"
            Clicked="Btn1_Clicked"
            StyleClass="style1,style2"
            Text="change image source" />

About StyleClass, please take a look:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/xaml/style-class

I think StyleClass is the new feature, so there are poorly documented.

Related