Xamarin Forms Button TextColor behaves differently

2019-03-31 22:39发布

I want a button's text color to be the same on both iOS and Android. So I thought I'd just set the TextColor property in code to the color I wanted. On iOS, the disabled text color is still grey (which is what I want), however, on Android, the disabled text color is the same as the enabled text color. How do I make the disabled text color on Android grey (or whatever its default is for a disabled button)? Thanks

2条回答
神经病院院长
2楼-- · 2019-03-31 22:56

If above does not work for you, you could try to check this workaround. It uses a custom renderer and NSAttributedString for setting the title in disabled state

查看更多
何必那么认真
3楼-- · 2019-03-31 23:03

That is the default behavior in Xamarin.Forms. To work around that and achieve a custom color, you can:

  • use triggers to change the color when going from enabled to disabled and vice versa
  • manually set the color when enabling and disabling the button
  • use a custom renderer

Because triggers are the most straightforward and consistent way of achieving what you want, I'll only cover that. You can see the xamarin docs for more information about custom renderers.

Using triggers, you can dynamically change the font color to gray when it is not enabled. See the docs for more information about triggers.

<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>
查看更多
登录 后发表回答