仅当某些条件为真时,才通过绑定将TextBlock设为粗体 [英] Make TextBlock Bold only if certain condition is true, via Binding
本文介绍了仅当某些条件为真时,才通过绑定将TextBlock设为粗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何通过Binding
到bool
将TextBlock
定义为粗体?
How can I define a TextBlock
as FontStyle
is Bold, via a Binding
to a bool
?
<TextBlock
Text="{Binding Name}"
FontStyle="???">
我真的很想将其绑定到
public bool NewEpisodesAvailable
{
get { return _newEpisodesAvailable; }
set
{
_newEpisodesAvailable = value;
OnPropertyChanged();
}
}
是否有办法实现这一目标,还是应该由我的Model属性为我完成翻译,而不是直接显示FontStyle
而不显示bool
?
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?
推荐答案
您可以通过DataTrigger
这样实现:
<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}}"/>
确保在XAML中将转换器声明为资源.
Make sure you declare converter as resource in XAML.
这篇关于仅当某些条件为真时,才通过绑定将TextBlock设为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文