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

心不动则不痛 提交于 2020-01-29 10:29:21

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


Use trigger in this case.

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

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



来源:https://stackoverflow.com/questions/20903720/make-textblock-bold-only-if-certain-condition-is-true-via-binding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!