在 Xamarin.Forms 中设置文本样式
样式可用于调整标签、条目和编辑器的外观。 样式可以定义一次,并由许多视图使用,但样式只能与一种类型的视图一起使用。
可以向样式提供 Key,并选择性地使用特定控件的 Style 属性应用样式。
内置样式
Xamarin.Forms 包括几种适用于常见方案的内置样式:
- BodyStyle
- CaptionStyle
- ListItemDetailTextStyle
- ListItemTextStyle
- SubtitleStyle
- TitleStyle
要应用其中一个内置样式,请使用 DynamicResource 标记扩展指定该样式:
<Label Text="I'm a Title" Style="{DynamicResource TitleStyle}"/>
在 C# 中,从 Device.Styles 中选择内置样式:
label.Style = Device.Styles.TitleStyle;

自定义央视
样式由 setter 组成,setter 则由属性和将这些属性设置为的值组成。
在 C# 中,大小为 30 的红色文本的标签自定义样式按以下方式定义:
var LabelStyle = new Style (typeof(Label)) {
    Setters = {
        new Setter {Property = Label.TextColorProperty, Value = Color.Red},
        new Setter {Property = Label.FontSizeProperty, Value = 30}
    }
};
var label = new Label { Text = "Check out my style.", Style = LabelStyle };
在 XAML 中:
<ContentPage.Resources>
    <ResourceDictionary>
        <Style x:Key="LabelStyle" TargetType="Label">
            <Setter Property="TextColor" Value="Red"/>
            <Setter Property="FontSize" Value="30"/>
        </Style>
    </ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
    <StackLayout>
        <Label Text="Check out my style." Style="{StaticResource LabelStyle}" />
    </StackLayout>
</ContentPage.Content>
请注意,资源(包括所有样式)是 ContentPage.Resources 中定义的,它是更熟悉的 ContentPage.Content 元素的同级元素。

应用样式
创建样式后,可将其应用于匹配其 TargetType 的任何视图。
在 XAML 中,将自定义样式应用于视图的方式是通过使用引用所需样式的 StaticResource 标记扩展来提供其 Style 属性:
<Label Text="Check out my style." Style="{StaticResource LabelStyle}" />
在 C# 中,样式可以直接应用于视图,也可以添加到页面的 ResourceDictionary 中并从中检索。 直接添加:
var label = new Label { Text = "Check out my style.", Style = LabelStyle };
要从页面的 ResourceDictionary 中添加和检索,请:
this.Resources.Add ("LabelStyle", LabelStyle);
label.Style = (Style)Resources["LabelStyle"];
内置样式以不同的方式应用,因为它们需要响应辅助功能设置。 要在 XAML 中应用内置样式,请使用 DynamicResource 标记扩展:
<Label Text="I'm a Title" Style="{DynamicResource TitleStyle}"/>
在 C# 中,从 Device.Styles 中选择内置样式:
label.Style = Device.Styles.TitleStyle;
辅助功能
内置样式的存在可以更轻松地遵循辅助功能首选项。 使用任何内置样式时,如果用户相应地设置其辅助功能首选项,字号将会自动增加。
请考虑在已启用和已禁用辅助功能设置的情况下,使用内置样式设置同一页面视图样式的以下示例:
禁用:

已启用:

要确保实现辅助功能,请确保将内置样式用作应用中任何文本相关样式的基础,并确保以一致的方式使用样式。 有关一般情况下扩展和使用样式的更多详细信息,请参阅样式。