【问题标题】:Make TextBlock Bold only if certain condition is true, via Binding仅当某些条件为真时,通过绑定使 TextBlock Bold
【发布时间】:2014-01-03 12:30:34
【问题描述】:

如何将TextBlock 定义为FontStyle 是粗体,通过Bindingbool

<TextBlock 
   Text="{Binding Name}"
   FontStyle="???">

我真的很想把它绑定到

public bool NewEpisodesAvailable
{
    get { return _newEpisodesAvailable; }
    set
    {
        _newEpisodesAvailable = value;
        OnPropertyChanged();
    }
}

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

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    您可以像这样通过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>
    

    或者您可以使用 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:

    <TextBlock FontWeight="{Binding IsEnable,
                            Converter={StaticResource BoolToFontWeightConverter}}"/>
    

    确保将转换器声明为 XAML 中的资源。

    【讨论】:

    • Nr1,谢谢详细信息,我会尝试一下,这两个概念对我来说都是新的。非常感谢!
    • 精彩的答案突出了两种非常有用的方法!
    【解决方案2】:

    只需实现一个转换器,将 bool 转换为您想要的字体样式。然后绑定到 NewEpisodesAvailable 并让您的转换器返回正确的值。

    【讨论】:

    • 请帮助我理解为什么这个提示被评为无用。这是使用小型转换器的完美示例。您是否期望完整的工作源代码或提示以便您可以继续?
    【解决方案3】:

    我将创建一个在其 getter 中返回字体样式的属性。如果您的上述属性为 false,您可以使其返回 null。然后将字体样式 xaml 绑定到该属性

    【讨论】:

      【解决方案4】:

      在这种情况下使用触发器。

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

      CodeProject 上的文章: http://www.codeproject.com/Tips/522041/Triggers-in-WPF

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-05
        • 2014-04-28
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        • 2019-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多