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}"
 FontAttributes="Bold"
 FontSize="16"
 HeightRequest="50"
 HorizontalOptions="Center"
 Text="{Binding StartText}"
 TextColor="White"
 VerticalOptions="Center"
 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,

 <converters:BoolToPercentConverter 
             x:Key="CanStartOpacityConverter"
 True="1"
 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 has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was 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 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

Comments are closed.