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!
One Response to Xamarin Quick Hit: Dimming a button to indicate it is disabled