【发布时间】:2011-10-22 15:33:08
【问题描述】:
您好我需要实现一个功能,如果绑定项的值在特定范围内,则单元格颜色应根据范围。
我一直在用Changing Background Color Of DataGrid Cell WPF 4
这很好用,但仅适用于存在该值的情况。如果我想添加范围,即 10 - 20 它是红色 21-30 它是蓝色的,该怎么办?
添加了所有内容并在最后看到了一个示例,但颜色没有改变这里是代码
类
public class ConvertToBrush : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int tempValue = int.Parse(value.ToString());
string tempString = "Red";
if (tempValue >= 0 && tempValue <= 20)
tempString = "#FF0000";
if (tempValue > 20 && tempValue <= 40)
tempString = "#F09300";
if (tempValue > 40 && tempValue <= 60)
tempString = "#EDDF00";
if (tempValue > 60 && tempValue <= 80)
tempString = "#FFFFFF";
if (tempValue > 80 && tempValue <= 100)
tempString = "#85AB00";
SolidColorBrush brush = new SolidColorBrush();
BrushConverter conv = new BrushConverter();
brush = conv.ConvertFromString(tempString) as SolidColorBrush;
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
XMAL
<DataGridTextColumn ElementStyle="{StaticResource CentreAlignStyle}" Binding="{Binding TestResults}" Header="Results" IsReadOnly="True" MaxWidth="60" MinWidth="60" >
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="TextBlock.Background" Value="{Binding TestResults, Converter={StaticResource makeBrush}}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
【问题讨论】:
-
你能重新阅读我的答案吗?就像我告诉你不要使用数据触发器而是直接绑定到背景的部分?
-
你能举例说明如何直接绑定吗?因为我是新手,我无法找到出路
-
真的没那么难,看我对答案的编辑。
标签: c# wpf xaml datagrid controls