您需要一个 ValueConverter 或一个 MultiValueConverter。下面是一个“应该”工作的简单示例,但是当我从记忆中编写它时,它可能有点错误,但应该给你一个想法。
[ValueConversion(typeof(decimal), typeof(Brush))]
public class BusVoltagesColorConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || !(value is decimal))
{
return DependencyProperty.UnsetValue;
}
var d = (decimal) value;
decimal lowerLimit = 0.95m; //TODO get your value from your user settings here
decimal upperLimit = 1.05m;
if (d < lowerLimit || d > upperLimit)
{
return Brushes.Red;
}
return Brushes.Black;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new BusVoltagesColorConverter();
}
}
然后在您的 WPF 页面上,您需要将其添加为资源。之后,它只是将转换器附加到前景或背景的数据绑定上。