Xamarin Forms – how to put a label grey if the related item is disabled

I was playing around with Xamarin Forms, and ran into a small hiccup :  Let’s say I have a list, and one particular item is disabled – what do I do ?

It’s easy to add a “Disabled” property to the associated ViewModel, and in the associated command check if it is disabled and if so, just return. But how do alter the visual state based on this property ?

A little searching brought me to this excellent article on http://pause.coffee/blog/ which gave me the answer.

I simply created a small class named GreyLabelIfDisabeldBehavior and here is it’s code:

    public class GreyLabelIfDisabledBehavior
    {
        public static readonly BindableProperty DisabledProperty = BindableProperty.CreateAttached<GreyLabelIfDisabledBehavior, bool>(
               bindable => GreyLabelIfDisabledBehavior.GetDisabled(bindable),
               false, /* default value */
               BindingMode.OneWay,
               null,
               (b, o, n) => GreyLabelIfDisabledBehavior.OnDisabledChanged(b, o, n),
               null,
               null);

        public static bool GetDisabled(BindableObject bo)
        {
            return (bool)bo.GetValue(GreyLabelIfDisabledBehavior.DisabledProperty);
        }

        public static void SetDisabled(BindableObject bo, Command value)
        {
            bo.SetValue(GreyLabelIfDisabledBehavior.DisabledProperty, value);
        }

        public static void OnDisabledChanged(BindableObject bo, bool oldValue, bool newValue)
        {
            if (oldValue != newValue)
            {
                var color = ColorEx.Render("foreground");
                if (newValue)
                    color = ColorEx.Render("gray");
                (bo as Label).TextColor = color;
            }
        }
    }

After that, it was a simple case of using the new feature in XAML like this:
<Label Text={Binding Title} customControls:GreyLabelIfDisabledBehavior.Disabled={Binding Disabled}/>

 
Comments

No comments yet.