我可以直接在<button>标签内设置按钮的字体大小吗?

时间:2017-07-25 15:15:26

标签: xamarin xamarin.forms

我有这段代码:

<Button x:Name="correctButton" HeightRequest="60" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
   <Button.FontSize>
       <OnPlatform x:TypeArguments="x:Double" x:Key="WindowBackgroundTable">
           <On Platform="Android" Value="20" />
           <On Platform="iOS" Value="25" />
       </OnPlatform>  
   </Button.FontSize>
</Button>

是否可以在没有

的情况下设置特定于平台的尺寸
<Button.FontSize>

2 个答案:

答案 0 :(得分:3)

不,如果你想为每个平台带来改变,你总是需要这样的额外代码。

通常情况下,您可以这样设置:<Button FontSize="25" x:Name="correctButton" HeightRequest="60" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" />

但是你无法区分平台的值。你可以做的,就像Anto提到的那样,是创造一种风格,并根据平台设定价值。你的代码在页面本身看起来会更清晰,但这个想法仍然是一样的。

为此,请在App.xaml中添加您的风格:

<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:TypeArguments="x:Double" x:Key="WindowBackgroundTable">
            <On Platform="Android" Value="20" />
            <On Platform="iOS" Value="25" />
        </OnPlatform>

        <Style TargetType="Button">
            <Setter Property="FontSize" Value="{DynamicResource WindowBackgroundTable}" />
        </Style>
    </ResourceDictionary>
</Application.Resources>

从您的FontSize中移除Button。 像这样,它是隐含的,您应用中的每个 Button都将被设置样式。

如果这不是您想要的,请将x:Key属性添加到Style标记,如下所示:<Style x:Key="ButtonStyle" TargetType="Button">

按照以下方式修改按钮:<Button Style="{StaticResource ButtonStyle}" Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />

答案 1 :(得分:1)

好吧,如果你只是没有嵌套标签,你可以走这条路:

<Label FontSize="{resources:PlatformedDouble Android=50, iOS=20}"></Label>

通过声明这样的标记扩展名:

public class PlatformedDouble : IMarkupExtension<double>
{
    public double Android { get; set; }

    public double iOS { get; set; }

    /// <inheritdoc />
    public double ProvideValue(IServiceProvider serviceProvider)
    {
        switch (Device.RuntimePlatform)
        {
            case Device.Android:
                return Android;
            case Device.iOS:
                return iOS;
        }

        return 42;
    }

    /// <inheritdoc />
    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return ProvideValue(serviceProvider);
    }
}
相关问题