DataGrid Column 的 Element Style 在 CodeBehind 中无效

DataGrid Column's Element Style in CodeBehind has no effect

我正在使用 MultiConverter 在后台代码中设置列的元素样式。尽管正在访问转换器并且完全没有错误,但单元格的背景没有得到更新。

private void DgBinding(DataTable dt)
{            
    string prevCol = "";

    foreach (DataColumn dc in dt.Columns)
    {
        if (dc.ColumnName.StartsWith("Delta"))
        {
            prevCol = dc.ColumnName;
            continue;
        }
        DataGridTextColumn col = new DataGridTextColumn
        {
            Header = dc.ColumnName,
            Binding = new Binding(dc.ColumnName)
        };

        this.dgTarget.Columns.Add(col);

        if (!string.IsNullOrEmpty(prevCol) && prevCol.StartsWith("Delta"))
        {
            MultiBinding m = new MultiBinding {Converter = new TimeSeriesColorConverter()};

            m.Bindings.Add(new Binding(dc.ColumnName));
            m.Bindings.Add(new Binding(prevCol));

            Style style = new Style();
            style.TargetType = typeof(TextBlock);

            Setter setter = new Setter
            {
                Property = BackgroundProperty,
                Value = m
            };

            style.Setters.Add(setter);

            col.ElementStyle = style;
        }
        prevCol = dc.ColumnName;
    }
}

如果我只是使用,col.CellStyle 它可以工作并且背景正在更新,但是使用 ElementStyle 根本没有效果。知道为什么吗?

我无法使用 XAML,因为数据是动态时间序列,列数未知。

您将 TargetType 用作 TextBlock,但是当在 setter 中设置 属性 时,您指的是 DataGridCell 的 BackgroundProperty。当 elemesntstyle 查找 TextBlock 更改时,它什么也没找到,也没有发生任何更改。

至于 CellStyle,Setter 是出于同样的原因。

将您的代码更改为:

         Setter setter = new Setter
            {
                Property = TextBlock.BackgroundProperty,
                Value = m
            };