【问题标题】:Xamarn.Forms Style or StyleClass?Xamarin.Forms 样式与样式类?
【发布时间】:2020-07-06 12:39:38
【问题描述】:

我一直在使用 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 之类的样式,这看起来很有用,但我想知道一直使用它是否会产生无法预料的后果。

谢谢

【问题讨论】:

    标签: xaml user-interface xamarin.forms


    【解决方案1】:

    常规样式遵循标准的、相对不灵活的 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 是新功能,所以文档很少。

    【讨论】:

    • 我不会说它们的文档记录很差,只是人们还没有适应样式类,因此不知道如何使用它们或何时使用它们!
    • 请注意 StyleClass 不是可绑定属性 afaik
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多