Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make TextBlock Bold only if certain condition is true, via Binding

Tags:

binding

wpf

How can I define a TextBlock as FontStyle is Bold, via a Binding to a bool?

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

And I'd really like to bind it to

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

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

like image 382
bas Avatar asked Jan 03 '14 12:01

bas


2 Answers

You can achieve that via DataTrigger like this:

    <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 will convert 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 converter as resource in XAML.

like image 171
Rohit Vats Avatar answered Oct 01 '22 18:10

Rohit Vats


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

like image 35
gomi42 Avatar answered Oct 01 '22 17:10

gomi42