Use a StyleSelector for a button

A more general way to accomplish the same thing:

SomeView.xaml

<UserControl>
  <UserControl.Resources>
    <converters:BooleanToStyleConverter x:Key="MyButtonStyleConverter" 
      TrueStyle="{StaticResource AmazingButtonStyle}" 
      FalseStyle="{StaticResource BoringButtonStyle}"/>
  </UserControl.Resources>
  <Grid>
    <Button Style={Binding IsAmazingButton, Converter={StaticResource MyButtonStyleConverter}}/>
  </Grid>
</UserControl>

BooleanToStyleConverter.cs

public class BooleanToStyleConverter : IValueConverter
{
    public Style TrueStyle { get; set; }
    public Style FalseStyle { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool && (bool) value)
        {
            return TrueStyle;
        }
        return FalseStyle;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This converter works in any view with any kind of control using whatever style you choose as long as you are binding to a Boolean property in your ViewModel to control the style switching. Easy to adapt it to other binding requirements though. This works in a DataTemplate as well.

Leave a Comment