Associate FontWeight with Boolean in Silverlight

Silverlight does not use DataTriggers, so in this case ... what could be the best way to conditionally set the font size of an element in boolean?

For example, in Silverlight, you cannot do the following.

<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!

+4
source share
3 answers

You can implement IValueConverter, which converts bool to FontWeight and uses it as a binding converter:

 <UserControl.Resources> <local:BoolToFontWeightConverter x:Key="boolToFontWeight"/> </UserControl.Resources> ... <TextBlock Text="{Binding Text}" FontWeight="{Binding IsDefault, Converter={StaticResource boolToFontWeight}}"> 
+10
source

I would use the 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 resources section, you would set 2 open 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 must install the converter, in this case, if IsCommentChange is True, the text will be red, if it is incorrect, then it is black.

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

Create your own IValueConverter, bind FontWeight to IsDefault and convert true to Bold and false to Normal

+1
source

All Articles