首页 > 解决方案 > 我可以在资源而不是渲染器中定义不同的文本样式吗?

问题描述

目前我正在使用这个渲染器来设置文本大小的样式:

<local:StyledLabel YAlign="Center" Text="Buttons" HorizontalOptions="StartAndExpand" />                     

public class StyledLabel : Label
{
    public StyledLabel()
    {
        if (Device.RuntimePlatform == Device.Android)
        {
            Style = Device.Styles.CaptionStyle;
        }
        else if (Device.RuntimePlatform == Device.iOS)
        {
            Style = Device.Styles.ListItemTextStyle;
        }
    }
}

有没有办法可以在资源 XAML 中执行类似的操作,以便 iOS 或 Android 的大小可能不同?

标签: xamarinxamarin.forms

解决方案


在 XAML 中,您可以指定不同的值,如下所示:

<local:StyledLabel YAlign="Center" Text="Buttons" HorizontalOptions="StartAndExpand" />
    <local:StyledLabel.Style>
        <OnPlatform x:TypeArguments="Style">
            <OnPlatform.Platforms>
                <On Platform="iOS" Value="{StaticResource CaptionStyle}" />
                <On Platform="Android" Value="{StaticResource ListItemTextStyle}" />
            </OnPlatform.Platforms>
        </OnPlatform>
    </local:StyledLabel.Style>
  ...
</local:StyledLabel>

此处的更多信息:https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/essential-xaml-syntax

顺便说一句,YAlign已弃用,您应该VerticalTextAlignment.


推荐阅读