I have done this using a simple converter on a property of the view model, for example lets say you had a boolean property that you wanted to control a style you could do this.
public class BoolToStyleConverter : IValueConverter
{
public Style TrueStyle{ get; set; }
public Style FalseStyle{ get; set; }
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((bool)value) ? TrueStyle : FalseStyle;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
then as a resource you would define your two styles...
<common:BoolToStyleConverter x:Key="BoldTextConverter">
<common:BoolToStyleConverter.TrueStyle>
<Style TargetType="TextBlock">
<Setter Property="FontWeight"
Value="Bold"></Setter>
</Style>
</common:BoolToStyleConverter.TrueStyle>
<common:BoolToStyleConverter.FalseStyle>
<Style TargetType="TextBlock">
<Setter Property="FontWeight"
Value="Normal"></Setter>
</Style>
</common:BoolToStyleConverter.FalseStyle>
</common:BoolToStyleConverter>
then you would apply it to your object like this...
<TextBlock Text="{Binding Description}"
Margin="20,4,4,4"
Style="{Binding IsConfirmed, Converter={StaticResource BoldTextConverter}}"></TextBlock>
Where IsConfirmed is a boolean property on the viewmodel, this will also keep the style in sync if the IsConfirmed
property changes.
If you want to use a more complicated condition than a Boolean you could always create a Dictionary of objects to Styles in your converter and then have the converter do a lookup, but i have found that usually booleans work in most cases.