更具体地说,我使用DataGrid只是为了显示应用操作历史记录。问题在于,对于用户来说,识别列太难了。所以我决定在循环颜色中逐个着色列,例如。第一个白色,第二个蓝色,第三个白色和...
由于我不太了解WPF标记,我通过下面的c#函数定义并应用了列:
private void generate_columns()
{
DataGridTextColumn c1 = new DataGridTextColumn();
c1.Header = "Shot number";
c1.Binding = new Binding("shotNum");
c1.Width = 80;
dataGrid.Columns.Add(c1);
DataGridTextColumn c2 = new DataGridTextColumn();
c2.Header = "Shooter name";
c2.Width = 160;
c2.Binding = new Binding("shooter");
dataGrid.Columns.Add(c2);
DataGridTextColumn c3 = new DataGridTextColumn();
c3.Header = "shot 1";
c3.Width = 120;
c3.Binding = new Binding("shoot1");
dataGrid.Columns.Add(c3);
DataGridTextColumn c4 = new DataGridTextColumn();
c4.Header = "shot 2";
c4.Width = 120;
c4.Binding = new Binding("shoot2");
dataGrid.Columns.Add(c4);
DataGridTextColumn c5 = new DataGridTextColumn();
c5.Header = "shot 3";
c5.Width = 120;
c5.Binding = new Binding("shoot3");
dataGrid.Columns.Add(c5);
DataGridTextColumn c6 = new DataGridTextColumn();
c6.Header = "Addition";
c6.Width = 180;
c6.Binding = new Binding("addition");
dataGrid.Columns.Add(c6);
DataGridTextColumn c7 = new DataGridTextColumn();
c7.Header = "Player1 score";
c7.Width = 160;
c7.Binding = new Binding("scoreh");
dataGrid.Columns.Add(c7);
DataGridTextColumn c8 = new DataGridTextColumn();
c8.Header = "Player2 score";
c8.Width = 160;
c8.Binding = new Binding("scoreo");
dataGrid.Columns.Add(c8);
}
其中c1,c2,...,c8是TextColumns,dataGrid是DataGrid的名称。 另外,在窗口启动时调用generate_columns()函数。
我的问题是我可以,如果我可以对上面的代码做什么改变,那么我可以控制颜色并按照我提到的方式改变它?
任何一些帮助或想法都受到高度重视
答案 0 :(得分:0)
如果您真的想在C#中进行,可以使用以下方法设置列的单元格颜色:
c1.CellStyle = new Style(typeof(DataGridCell));
c1.CellStyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.LightBlue)));
所以,如果你想做交替的颜色,一个快速的方法是:
for (int i = 0; i < dataGrid.Columns.Count; i++)
{
var desiredColor = new SolidColorBrush(i % 2 == 0 ? Colors.White : Colors.LightBlue);
dataGrid.Columns[i].CellStyle = new Style(typeof(DataGridCell));
dataGrid.Columns[i].CellStyle.Setters.Add(new Setter(BackgroundProperty, desiredColor));
}
i % 2 == 0 ?
用于替换偶数和奇数的颜色