Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Styling In Silverlight?

While I'm fine with standard control styling in silverlight I have recently began using more dynamic methods of fetching data to be displayed in items controls. One of the controls I am reworking is a collection of links.

The issue I am having is that each link is coloured differently when moused over. One red, one blue, one green, etc. Is there a way to style these items without sacrificing the dynamics of using an items control with a data template?

like image 373
deanvmc Avatar asked Jun 13 '10 23:06

deanvmc


1 Answers

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.

like image 172
luke Avatar answered Oct 20 '22 23:10

luke