更新时间:2022-06-02 02:56:30
在将前景颜色绑定到一段数据时,通常有两种很好的方法供您选择.根据您询问的对象,不同的人会有不同的偏好.所以……两者都有!
There are generally two good approaches for you to choose from, when binding the Foreground color to a piece of data. Depending on who you ask, different people will have different preferences. So... here's both!
当满足一组特定条件时,此方法基本上可以识别特殊"行为.在这种情况下,我们将前景色更改为灰色,当状态 ==无需维护"
This method basically identifies 'special' behavior when a certain set of conditions are met. In this case, we're changing the foreground color to Gray, when the status == "No Maintenance Required"
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Black" /> <!-- default value -->
<Style.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}" Value="No Maintenance Required">
<Setter Property="Foreground" Value="Gray" /> <!-- special behavior -->
</DataTrigger>
</Style.Triggers>
</Style>
在这种情况下,只需为您的 TextBlock 分配适当的 Style
属性.
In this case, just assign your TextBlock the appropriate Style
property.
这种方法创建了一个自定义的IValueConverter 实现,它将您的文本值转换为颜色.从那里,我们直接绑定到我们的文本值,并确保转换器始终提供正确的颜色.
This approach creates a custom "IValueConverter implementation, which converts your Text value to a Color. From there, we bind directly to our text value, and ensure that the converter always provides the proper color.
public class MaintenaceColorConverter : IValueConverter
{
public Color NormalColor { get; set; }
public Color NoMaintenanceRequiredColor { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.ToString() == "No Maintenance Required")
return NoMaintenanceRequiredColor;
return NormalColor;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在您的 XAML 中:
In your XAML:
<Window.Resources>
<local:MaintenaceColorConverter x:Key="myColorConverter" NormalColor="Black" NoMaintenanceRequiredColor="Gray" />
</Window.Resources>
在您的文本块中:
<TextBlock Text="{Binding MaintStatus}" Foreground="{Binding MaintStatus, Converter={StaticResource myColorConverter}}" />
使用这些方法中的任何一种,***有一个 MaintenanceStatus
布尔值或枚举值,并将您的样式条件绑定到该值.使用字符串比较是一个坏主意.那只是自找麻烦.这些示例使用了字符串比较,因为……好吧……这就是您提供的示例代码中的全部内容.
With either of these approaches, it would be better to have a MaintenanceStatus
boolean or enum value, and bind your styling conditions to that. It's a bad idea to use string-comparisons. That's just begging for trouble. These examples used string comparison because... well... that's all that was available from your provided example code.