【发布时间】:2022-01-04 19:45:22
【问题描述】:
我正在使用以下代码以编程方式更改 DataGrid 的列颜色:
this.ImportPreview.Columns[index].CellStyle = new Style(typeof(DataGridCell));
this.ImportPreview.Columns[index].CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new SolidColorBrush(Colors.LightBlue)));
这对每一列都有效。如果我再次尝试更改它,Setter Collection 将被锁定。
出现以下错误:
System.InvalidOperationException:
'After a 'SetterBaseCollection' is in use (sealed), it cannot be modified.'
我尝试清除 setter 集合,结果相同:
this.ImportPreview.Columns[index].CellStyle.Setters.Clear();
我找到了以下有希望的问题/答案,但答案对我来说是简写的。我不知道如何应用这个答案: How to add further style setters programmatically? When I try I got an InvalidOperationException exception (SetterBaseCollection is in use)
此外,还有很多类似的问题,但它们是基于在 xaml 中设置样式,而我正在尝试以编程方式进行。
【问题讨论】: