首页 > 解决方案 > Xamarn.Forms 样式还是 StyleClass?

问题描述

我一直在使用 Xamarin.Forms 应用程序,我注意到我有两个应用样式的选项。我可以创建一个具有“类”属性的样式,并将其与元素“StyleClass”属性一起使用,如下所示:

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

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

或者,我可以使用“x:Key”编写样式并将其与“样式”属性设置为静态资源一起使用:

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

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

任何一个似乎都有效,但我不知道一般使用哪个,而且我找不到关于它们用途的适当文档。StyleClass 是一个 IList,我相信它会应用 CSS 之类的样式,这似乎很有用,但我想知道是否一直使用它会产生无法预料的后果。

谢谢

标签: xamluser-interfacexamarin.forms

解决方案


常规样式遵循标准的、相对不灵活的 WPF 模型。

可以通过将 Style 上的 Class 属性设置为表示类名的字符串来创建样式类。与使用 x:Key 属性定义显式样式相比,它提供的优势在于可以将多个样式类应用于 VisualElement。

多个样式可以共享相同的类名,前提是它们针对不同的类型。这使多个同名的样式类能够针对不同的类型。

就像下面的代码:

<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>

多个样式类可以应用于一个控件,因为 StyleClass 属性是 IList 类型。

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

关于StyleClass,请看:

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

我认为 StyleClass 是新功能,因此文档很少。


推荐阅读