Question

Silverlight does not feature DataTriggers, so in this case... what might be the best way to conditionally set the fontweight of an item to a boolean?

For example... the following is not possible in Silverlight.

<TextBlock Text="{Binding Text}">
    <TextBlock.Triggers>
        <DataTrigger Binding="{Binding IsDefault}" Value="True">
            <Setter Property="FontWeight" Value="Bold"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding IsDefault}" Value="False">
            <Setter Property="FontWeight" Value="Normal"/>
        </DataTrigger>
    </TextBlock.Triggers>
</TextBlock>

Thanks!

Was it helpful?

Solution

You could implement a IValueConverter that converts a bool to a FontWeight, and use it as the binding's converter :

<UserControl.Resources>
    <local:BoolToFontWeightConverter x:Key="boolToFontWeight"/>
</UserControl.Resources>

...

<TextBlock Text="{Binding Text}" FontWeight="{Binding IsDefault, Converter={StaticResource boolToFontWeight}}">

OTHER TIPS

I would actually use a Boolean to Style converter.

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

    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();
    }
}

Then in the resource section you would set the 2 public style properties.

<localHelpers:BoolToStyleConverter x:Key="boolToHistoryTextBlockStyleConverter">
    <localHelpers:BoolToStyleConverter.TrueStyle>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red"></Setter>
        </Style>
    </localHelpers:BoolToStyleConverter.TrueStyle>
    <localHelpers:BoolToStyleConverter.FalseStyle>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Black"></Setter>
        </Style>
    </localHelpers:BoolToStyleConverter.FalseStyle>
</localHelpers:BoolToStyleConverter>

This example sets the Foreground color, but you can set any style. To bind this you would set the converter, in this case if IsCommentChange is True the text will be in red, if it is false then it is black.

    <TextBlock Name="tbComment" Text="{Binding Path=Comment,Mode=OneTime}"
 TextWrapping="Wrap"  
    Style="{Binding Path=IsCommentChanged, 
    Converter={StaticResource boolToHistoryTextBlockStyleConverter}}" />

Create a custom IValueConverter, bind the FontWeight to IsDefault, and convert true to Bold and false to Normal

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top