简体   繁体   中英

DataGrid Column's Element Style in CodeBehind has no effect

I am setting column's Element style in code behind using MultiConverter. Even though the converter is being accessed and there's no error at all, cell's background is not getting updated.

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;
    }
}

If I just use, col.CellStyle it works and the background's are getting updated, but with ElementStyle there's no effect at all. Any idea why?

I can't use XAML as the data is dynamic timeseries and # of Columns are unknown.

You are using TargetType as TextBlock but when setting the property inside setter you are referring to DataGridCell's BackgroundProperty . When elemesntstyle looks for TextBlock changes, it finds nothing and no change occurs.

As for CellStyle, Setter works because of the same reason.

Change your code to this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM