按 Cellvalue 为 DataGridCell 着色

Color DataGridCell by Cellvalue

我有一个列数不同的 WPF DataGrid。我想根据值为单个单元格着色。 例如:如果单元格值为 0,则为红色。

这些是我的实验:

<DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" x:Name="DataGrid"  SelectionUnit="Cell">
        <DataGrid.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                  <!--experiment 1 -->
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Value, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Value="0">
                        <Setter Property="Background" Value="LimeGreen"/>
                    </DataTrigger>
                   <!--experiment 2 -->
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Content, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Value="0">
                        <Setter Property="Background" Value="LimeGreen"/>
                    </DataTrigger>
                    </Style.Triggers>
            </Style>
        </DataGrid.CellStyle>
</DataGrid>

只需使用一个值转换器(以单元格值作为参数),returns您想要的颜色。

<DataGrid>
    <DataGridCell Background="{Binding CellValueField, Converter={StaticResource YourDefinedValueToColorConverter}}" />
</DataGrid>

编辑:终于让它工作了。

转换器和样式定义:

<Window.Resources>
    <c:ValueToColorConverter x:Key="ValueToColorConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToColorConverter}}" />
    </Style>
</Window.Resources>

数据网格:

<DataGrid HorizontalAlignment="Left"
              Margin="10,10,0,0"
              VerticalAlignment="Top"
              Loaded="DataGrid_Loaded">
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="Background" Value="{Binding Converter={StaticResource ValueToColorConverter}}" />
            </Style>
        </DataGrid.CellStyle>
    </DataGrid>

和转换器:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var cell = value as Order;
        if (cell != null && cell.Size > 80)
            return new SolidColorBrush(Colors.Red);
        else return new SolidColorBrush(Colors.Yellow);
    }

我使用 DataGrid_Loaded 方法用封装在示例中的一些随机数据填充 DataGrid class:

class Order
{
    public int Size { get; set; }
}

结果:

使用值转换器,像这样:

<DataGridCell Background="{Binding CellValueField, Converter={StaticResource IntegerToColorValueConverter}}" />

并且:

public class IntegerToColorValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
          System.Globalization.CultureInfo culture)
    {
        switch ((int)value)
        {
            case 1: return Color.Red; break;
            case 2: return Color.Yellow; break;
            Default: return Color.White; break;
        }
    }

}