Xamarin Quick Hit: Dimming a button to indicate it is disabled

I often have to dim a button to indicate that it is disabled, and I want to do that via data binding.

Thus, I want my button to look more or less like this:

 <Button x:Name="StartButton"
 Opacity="{Binding CanStart, 
    Converter={StaticResource CanStartOpacityConverter}}"
 Command="{Binding StartCommand}"
 Text="{Binding StartText}"
 WidthRequest="116" />

The key line is the second, where the opacity is bound to a property, CanStart and converted by the CanStartOpacityConverter.

The CanStart is a standard boolean property.

The magic is in the converter.  For this, I wrote the following custom converter, which is designed to take in a bool and spit out a percentage:


   public class BoolToPercentConverter : IValueConverter
      public double True { get; set; }

      public double False { get; set; }

      public object Convert(object value, Type targetType, 
object parameter, System.Globalization.CultureInfo culture)
         if (value == null)
            return False;
         if (value.GetType() != typeof(bool))
            return False;
         return ((bool)value) ? True : False;

      public object ConvertBack(object value, 
Type targetType, 
object parameter, 
System.Globalization.CultureInfo culture)
         return value;

This allows me to create an instance of the converter, setting the percent value for True and False,

 False="0.4" />

Now, to dim the button, all I have to do is set CanStart to false and its opacity is set to 40%

Remember, this is only the UI, you still have to disable the button!


About Jesse Liberty

Jesse Liberty is a Senior Consultant with Wintellect, with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight & LinkedIn Learning courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Essentials, Learning, Xamarin, XAML and tagged . Bookmark the permalink.

One Response to Xamarin Quick Hit: Dimming a button to indicate it is disabled

  1. Jeff R. says:

    Hi, thanks for this post, I like it and can think of a number of things this would be useful for. For this specific example though, wouldn’t a Trigger be more useful? For example, have it based on IsEnabled and do the dimming? You could still bind IsEnabled to the CanStart property.

    I admit I’m still very new to Xamarin so maybe I’m mixing up too much WPF…

Leave a Reply

Your email address will not be published. Required fields are marked *