更改DataGrid Cell WPF的颜色范围 [英] Change color of DataGrid Cell WPF regarding Range
问题描述
我需要实现一个功能,如果绑定项的值在特定范围内,则单元格颜色应该是根据范围。
Hi I need to implement a function that if the value of the binding items is within the specific range cell color should be according to the range.
我已经使用更改DataGrid Cell WPF 4的背景颜色
这个工作很好,但只有当这些值在那里时才是。如果我想添加范围,即从10到20,它是红色21-30它是蓝色的
this works fine but it is for only if that values are there.what if i want to add range i.e from 10 - 20 it is red 21-30 it is blue
添加了一切,最后看到一个例子,但这里的颜色不改变是代码
added everything and saw an example at the end but the color does not change here is the code
类
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>
推荐答案
不要使用 DataTrigger
,但只需将背景
绑定到该值并放入 ValueConverter
返回正确的画笔(或根本没刷)
Don't use a DataTrigger
but just bind the Background
to the value and put in a ValueConverter
to return the right brush (or no brush at all).
编辑:使用情况应如下所示:
What the usage should look like:
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="Border.Background" Value="{Binding TestResults, Converter={StaticResource BrushConverter}}" />
</Style>
</DataGridTextColumn.CellStyle>
这篇关于更改DataGrid Cell WPF的颜色范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!