问题
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