Xamarin Forms Button TextColor 在 Android 上的行为不同于 iOS

Xamarin Forms Button TextColor behaves differently on Android than an iOS

我希望 iOS 和 Android 上的按钮文本颜色相同。所以我想我只是将代码中的 TextColor 属性 设置为我想要的颜色。在 iOS 上,禁用的文本颜色仍然是灰色(这是我想要的),但是在 Android 上,禁用的文本颜色与启用的文本颜色相同。如何使 Android 灰色(或禁用按钮的默认设置)上的禁用文本颜色? 谢谢

这是 Xamarin.Forms 中的默认行为。要解决此问题并实现自定义颜色,您可以:

  • 在从启用到禁用时使用触发器更改颜色,反之亦然
  • 启用和禁用按钮时手动设置颜色
  • 使用自定义渲染器

因为触发器是实现您想要的东西的最直接和最一致的方式,所以我将只介绍它。您可以查看 xamarin docs 以获取有关自定义渲染器的更多信息。

使用触发器,您可以在未启用时将字体颜色动态更改为灰色。有关触发器的更多信息,请参阅 docs

<Button Text="I am a Button">
<Button.Triggers>
    <Trigger TargetType="Button"
         Property="IsEnabled" Value="true">
        <Setter Property="TextColor" Value="Red" />
        <!-- red is the desired color when the button is enabled.-->
    </Trigger>
    <Trigger TargetType="Button"
         Property="IsEnabled" Value="false">
        <Setter Property="TextColor" Value="Gray" />
        <!-- gray is the desired color when the button is disabled.-->
    </Trigger>
</Button.Triggers>
</Button>

如果以上方法不适合您,您可以尝试查看this workaround。它使用自定义渲染器和 NSAttributedString 将标题设置为禁用状态