1

In my Xamarin Forms app, I have a DatePicker that can appear as disabled. On Android, the DatePicker renders the text as black when the DatePicker is disabled. Due to a dark background, I'd like to change that color to gray.

I have tried many approaches in my custom renderer, but I have not been able to figure it out. I've even tried ColorStateList to no avail. I can't set it in styles because the background color can change between light and dark.

What is the proper approach to change the color of the date field when a DatePicker is disabled?

2 Answers 2

4

You can use a Custom Renderer and override OnElementPropertyChanged to change the Text Color anytime IsEnabled is toggled.

Android Custom Renderer

using Android.Content;

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

using CustomDatePicker.Droid;

[assembly: ExportRenderer(typeof(Picker), typeof(DisabledDatePickerRenderer))]
namespace CustomDatePicker.Droid
{
    public class DisabledDatePickerRenderer : DatePickerRenderer
    {
        public DisabledDatePickerRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName.Equals(nameof(Element.IsEnabled)) && Control != null)
            {
                if (Element.IsEnabled)
                {
                    //Set the text color when the DatePicker is enabled
                    Control.SetTextColor(Android.Graphics.Color.Black);
                }
                else
                {
                    //Set the text color when the DatePicker is disabled
                    Control.SetTextColor(Android.Graphics.Color.Gray);
                }
            }
        }
    }
}
0
-2

A more modern solution would be to use the AppThemeBinding extension that allows responding in real-time to app theme changes. You can also use it in code-behind, such as in a custom renderer, using the SetAppThemeColor() extension method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.