仅当某些条件为真时才通过Binding使TextBlock Bold

bas*_*bas 10 wpf binding

我怎样才能定义TextBlockFontStyle是勇敢的,通过Binding一个bool

<TextBlock 
   Text="{Binding Name}"
   FontStyle="???">
Run Code Online (Sandbox Code Playgroud)

我真的很想把它绑定

public bool NewEpisodesAvailable
{
    get { return _newEpisodesAvailable; }
    set
    {
        _newEpisodesAvailable = value;
        OnPropertyChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一点,或者我的Model属性应该为我做翻译,而不是直接呈现bool礼物FontStyle

Roh*_*ats 29

您可以通过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>
Run Code Online (Sandbox Code Playgroud)

或者您可以使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<TextBlock FontWeight="{Binding IsEnable,
                        Converter={StaticResource BoolToFontWeightConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

确保在XAML中将转换器声明为资源.