Make a TextBlock Bold only if a certain condition is true, through Binding

How can I define a TextBlock as FontStyle Bold using Binding to bool ?

 <TextBlock Text="{Binding Name}" FontStyle="???"> 

And I really would like to tie him to

 public bool NewEpisodesAvailable { get { return _newEpisodesAvailable; } set { _newEpisodesAvailable = value; OnPropertyChanged(); } } 

Is there a way to achieve this, or should my Model property make a translation for me, instead of representing the bool directly to FontStyle ?

+6
source share
4 answers

You can achieve this through a DataTrigger as follows:

  <TextBlock> <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Binding="{Binding NewEpisodesAvailable}" Value="True"> <Setter Property="FontWeight" Value="Bold"/> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> 

Or you can use IValueConverter , which converts bool to FontWeight.

 public class BoolToFontWeightConverter : DependencyObject, IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return ((bool)value) ? FontWeights.Bold : FontWeights.Normal; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return Binding.DoNothing; } } 

XAML:

 <TextBlock FontWeight="{Binding IsEnable, Converter={StaticResource BoolToFontWeightConverter}}"/> 

Make sure you declare the converter as a resource in XAML.

+17
source

Just implement a converter that converts bool to your desired font style. Then bind to NewEpisodesAvailable and let your converter return the correct value.

+2
source

I would create a property that returns the font style in its getter. You can return it if your property is higher than false. Then bind the xaml font style to this property

+1
source

In this case, use a trigger.

 <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Binding="{Binding NewEpisodesAvailable}" Value="True"> <Setter Property="FontWeight" Value="Bold"/> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> 

CodeProject article: http://www.codeproject.com/Tips/522041/Triggers-in-WPF

+1
source

All Articles