Células DataGrid-cores do WPF na escala de cores graduadas
de momento, configurei a propriedade de fundo das colunas do datagrid para ligar ao seguinte Conversor:
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();
}
}
}
Existe uma maneira, sem codificação dos valores, de obter uma escala de cores?
Obrigado, kcross.Editar: também estou a tentar criar uma cor Vermelho-Verde melhor escala (ou seja, para números negativos a positivos), em termos de um que é um pouco menos difícil para os olhos.... se alguém tem alguma sugestão sobre isso, bem que também é apreciado!
1 answers
Background="{Binding Path=YourDoubleValue,
Converter={StaticResource ValueToBrushConverter},
ConverterParameter='YourMinDouble|YourMaxDouble'}"
Isto irá criar uma escala de cores gradiente de verde (YourMinDouble
) para vermelho (YourMaxDouble
) e escolher a cor relacionada para YourDoubleValue
. YourMinDouble
pode ser negativo, mas tem de ser menor do que YourMaxDouble
. Se YourDoubleValue
não estiver dentro do intervalo, devolve Brushes.Transparent
.
Personalize-o para as suas necessidades!
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();
}
}