Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a requirement to change a button's style based on a value in the data. It looks like a StyleSelector would work perfectly but there doesn't seem to be a way to set one for a button.

Is there a way to set a button style dynamically from data? Maybe even a pure XAML approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...