我正在试图弄清楚是否有办法在色标上对单个细胞进行着色。特别是,我希望在下面得到类似Bonus专栏的内容:
目前,我已将我的datagrid列的后台属性设置为绑定到以下转换器:
public class NameToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double? input = value as double?;
if(input<-5)
{
return Brushes.MediumVioletRed;
}
if(-5<=input && input<-0.5)
{
return Brushes.IndianRed;
}
if (.5 <= input && input < 5)
{
return Brushes.LightGreen;
}
if (5 <= input)
{
return Brushes.LawnGreen;
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
有没有办法在没有硬编码值的情况下获得色标?
谢谢 - kcross
编辑:我也试图创造一个更好的红绿色标度(即负数到正数),对于眼睛稍微不那么难的一个......如果有人有什么建议的话对此也表示赞赏!
答案 0 :(得分:4)
我创建了一个ValueToBrushConverter。你这样使用它:
Background="{Binding Path=YourDoubleValue,
Converter={StaticResource ValueToBrushConverter},
ConverterParameter='YourMinDouble|YourMaxDouble'}"
这将创建从绿色(YourMinDouble
)到红色(YourMaxDouble
)的渐变色标,并选择YourDoubleValue
的相关颜色。 YourMinDouble
可以是否定的,但必须小于YourMaxDouble
。如果YourDoubleValue
不在范围内,则会返回Brushes.Transparent
根据您的需求定制它!
<强> ConverterClass 强>
[ValueConversion(typeof(double), typeof(Brush))]
class ValueToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double number = (double)value;
double min = 0;
double max = 100;
// Get the value limits from parameter
try
{
string[] limits = (parameter as string).Split(new char[] { '|' });
min = double.Parse(limits[0], CultureInfo.InvariantCulture);
max = double.Parse(limits[1], CultureInfo.InvariantCulture);
}
catch (Exception)
{
throw new ArgumentException("Parameter not valid. Enter in format: 'MinDouble|MaxDouble'");
}
if (max <= min)
{
throw new ArgumentException("Parameter not valid. MaxDouble has to be greater then MinDouble.");
}
if (number >= min && number <= max)
{
// Calculate color channels
double range = (max - min) / 2;
number -= max - range;
double factor = 255 / range;
double red = number < 0 ? number * factor : 255;
double green = number > 0 ? (range - number) * factor : 255;
// Create and return brush
Color color = Color.FromRgb((byte)red, (byte)green, 0);
SolidColorBrush brush = new SolidColorBrush(color);
return brush;
}
// Fallback brush
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}