Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

.net - Use a StyleSelector for a button

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...