动态设置textblock的字体颜色
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding IsSuccess, Converter={StaticResource BoolToSuccessConverter}}"
Foreground="{Binding IsSuccess,Converter={StaticResource BoolToColorConverter}}">
</TextBlock>
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
McsfRestoreLogger.WriteLog("[BoolToColorConverter]: value is null.");
return false;
}
else
{
if ((bool)value)
{
return "green";
}
else
{
McsfRestoreLogger.WriteLog("[BoolToColorConverter]: value is ." + value);
return "red";
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
方式二
Value="Success"值根据实际情况填
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Self}}" Value="Success">
<Setter Property="Foreground" Value="Green" />
</DataTrigger>
<DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Self}}" Value="Failed">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>