样式
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中,通过为Style
属性提供带有StaticResource
所需样式的标记扩展名,将自定义样式应用于视图:
<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;
无障碍
存在内置样式以使其更容易遵守辅助功能偏好。当使用任何内置样式时,如果用户相应地设置其辅助功能选项,则字体大小将自动增加。
请考虑以下具有内置样式风格的视图的相同页面的示例,启用和禁用辅助功能设置:
禁用:
启用:
为了确保可访问性,请确保内置样式被用作应用程序中任何文本相关样式的基础,并且您一直使用样式。有关扩展和使用样式的详细信息,请参阅样式。