通过 WPF 转换器更改字体颜色



在我的xaml中,我有标签:

<Label Content="{Binding Path=HSValidation, Converter={StaticResource HSFontConverter}}" />

进入转换器,我想将标签字体更改为"RED":

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{           
  if (value != null)
   {
       return value; //should be value with changed color       
   }          
  return value;  
}

我可以只使用 C# 代码吗?

还是我需要标签的名称属性?

转换器

仅将源值转换为其他值,因此您只能使用绑定将"Content"属性转换为其他内容。

因此,您应该将内容绑定到

现有内容,然后将"前景"属性绑定到颜色。

<Label 
    Content="{Binding Path=HSValidation}" 
    Foreground="{Binding Path=HSValidation, Converter={StaticResource HSFontConverter}}" />

例如,您应该在转换器代码中返回 Brushes.Red,并在转换器中的所有分支上返回 Brush,而不是绑定值:

public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{           
    if (value != null)
    {
        return Brushes.Red;
    }          
    return Brushes.Black;  
}

最新更新