You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中为动态创建的DataGrid列设置单元格背景色问题

解决方案:绑定十六进制颜色值到DataGrid单元格背景

要实现将DataItem的十六进制Color属性动态转换为单元格背景色,核心是通过**值转换器(ValueConverter)**把字符串格式的十六进制颜色值转换成WPF可识别的Brush对象,再通过绑定应用到单元格样式中。

步骤1:创建十六进制转Brush的转换器

实现IValueConverter接口,处理十六进制字符串到SolidColorBrush的转换,兼容带#和不带#的常见格式:

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

public class HexColorToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string hexColor)
        {
            // 自动补全#前缀(如果输入不带的话)
            if (!hexColor.StartsWith("#"))
                hexColor = $"#{hexColor}";
            
            // 尝试转换为Color并包装成SolidColorBrush
            if (ColorConverter.ConvertFromString(hexColor) is Color color)
                return new SolidColorBrush(color);
        }
        
        // 转换失败时返回透明背景(可根据需求调整为默认色)
        return Brushes.Transparent;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // 无需反向转换时返回Binding.DoNothing
        return Binding.DoNothing;
    }
}

步骤2:为Percentage列应用转换器和绑定

修改LoadDataGridElements方法,在创建Percentage列后,为其单元格样式绑定Color属性并指定转换器:

private void LoadDataGridElements(List<DataItem> items)
{
    grid.ItemsSource = null;
    grid.Items.Clear();
    grid.Columns.Clear();
    grid.ItemsSource = items;

    DataGridTextColumn column = null;

    NewColumn(grid, "Name", true, "Name");
    column = NewColumn(grid, "Percentage", false, "Percentage");

    // 配置Percentage列的单元格背景绑定
    column.CellStyle = new Style(typeof(DataGridCell))
    {
        Setters = 
        {
            new Setter
            {
                Property = DataGridCell.BackgroundProperty,
                Value = new Binding("Color")
                {
                    Converter = new HexColorToBrushConverter()
                }
            }
        }
    };
}

关键说明

  • 转换器支持多种十六进制格式:#FF0000、FF0000、#F00、F00都能正确转换。
  • 若你的Color属性格式固定(比如始终带#),可移除转换器中的前缀补全逻辑简化代码。
  • 转换失败时默认返回透明背景,可根据业务需求替换为其他默认颜色(如Brushes.White)。

内容的提问来源于stack exchange,提问作者Yakuman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 18:35:02