gpt4 book ai didi

c# - WPF DataGrid - 分级色标上的颜色单元格

转载 作者:行者123 更新时间:2023-11-30 15:39:35 24 4
gpt4 key购买 nike

我想弄清楚是否有办法在色标上为单个单元格着色。特别是,我希望在以下内容中获得类似 Bonus 列的内容:

Color scale example

目前,我已经将我的数据网格的列背景属性设置为绑定(bind)到以下转换器:

        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

编辑:我也在尝试创建一个更好的红绿色标(即从负数到正数),就眼睛而言不那么难受的色标....如果有人有任何建议对此也表示赞赏!

最佳答案

我创建了一个 ValueToBrushConverter。你可以这样使用它:

Background="{Binding Path=YourDoubleValue,
Converter={StaticResource ValueToBrushConverter},
ConverterParameter='YourMinDouble|YourMaxDouble'}"

这将创建一个从绿色 (YourMinDouble) 到红色 (YourMaxDouble) 的渐变色标,并为 YourDoubleValue 选择相关颜色。 YourMinDouble 可以是负数,但必须小于 YourMaxDouble。如果 YourDoubleValue 不在范围内,则返回 Brushes.Transparent
根据您的需要定制它!

转换器类

[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();
}
}

关于c# - WPF DataGrid - 分级色标上的颜色单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10216582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com