CodeBehind 中 DataGrid 列的元素样式不起作用



我正在使用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
            };

最新更新