wpf 仅当某些条件为真时才使 TextBlock 加粗,通过绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20903720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make TextBlock Bold only if certain condition is true, via Binding
提问by bas
How can I define a TextBlockas FontStyleis Bold, via a Bindingto a bool?
如何通过 a到 a将 a 定义TextBlock为FontStyle粗体?Bindingbool
<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 boolpresent the FontStyledirectly?
有没有办法实现这一点,或者我的模型属性应该为我做翻译,而不是直接呈现bool礼物FontStyle?
回答by Rohit Vats
You can achieve that via DataTriggerlike this:
您可以通过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 IValueConverterwhich will convert bool to FontWeight.
或者您可以使用IValueConverter将 bool 转换为 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:
XAML:
<TextBlock FontWeight="{Binding IsEnable,
Converter={StaticResource BoolToFontWeightConverter}}"/>
Make sure you declare converter as resource in XAML.
确保在 XAML 中将转换器声明为资源。
回答by gomi42
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.
只需实现一个转换器,将 bool 转换为您想要的字体样式。然后绑定到 NewEpisodesAvailable 并让您的转换器返回正确的值。
回答by Anthony Russell
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
我将创建一个属性,在其 getter 中返回字体样式。如果您的上述属性为 false,您可以使其返回 null。然后将字体样式 xaml 绑定到该属性
回答by Valera Scherbakov
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
关于 CodeProject 的文章:http: //www.codeproject.com/Tips/522041/Triggers-in-WPF

