当列被定义并添加为 c# 代码时,如何为 wpf 数据网格的列着色?

How to color the columns of a wpf datagrid when columns are defined and added be c# code?

更具体地说,我将 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() 函数在 window 启动时被调用。

我的问题是我可以吗?如果可以的话,我应该对上面的代码做些什么更改,以便我可以控制颜色并按照我提到的方式进行更改?

任何一点帮助或想法都受到高度重视

如果您真的想在 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 ?用于偶数和奇数交替显示颜色