wpf 如何在后面的代码中设置 DataGrid 行的背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22206402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:07:58  来源:igfitidea点击:

How to set the background color of a DataGrid row in code behind?

c#wpf

提问by John Threepwood

I create a DataGridobject in my code behind and set the content with obj.ItemsSource.

DataGrid在后面的代码中创建了一个对象,并将内容设置为obj.ItemsSource.

Now I would like to set the background color of one specific row in the code behind. How can I achieve this?

现在我想在后面的代码中设置一个特定行的背景颜色。我怎样才能做到这一点?

Update:

更新:

I create the DataGridobject in the code behind like following:

DataGrid在后面的代码中创建对象,如下所示:

var dataGrid = new DataGrid();
dataGrid.ItemsSource = BuildDataGrid(); // Has at least one row
var row = (DataGridRow) dataGrid.ItemContainerGenerator.ContainerFromIndex(0);
row.Background = Brushes.Red;

But the rowobject is null. Why is that?

row对象是null。这是为什么?

回答by Rohit Vats

You can get the DataGridRowusing ItemContainerGeneratorof dataGrid.

您可以获取dataGrid的DataGridRowusing ItemContainerGenerator

In case you want to select row based on index value, use ContainerFromIndex()method:

如果要根据索引值选择行,请使用ContainerFromIndex()方法:

DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
                    .ContainerFromIndex(0);

and in case want to get row based on item, use ContainerFromItem()method:

如果想根据项目获取行,请使用ContainerFromItem()方法:

DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
                    .ContainerFromItem(item);

Finally set background on row:

最后在行上设置背景:

row.Background = Brushes.Red;


UPDATE:

更新

Containers are not generated till dataGrid is not visible on GUI. You need to wait for containers to be generated before you can set any property on DataGridRow.

在 GUI 上看不到 dataGrid 之前,不会生成容器。您需要等待容器生成,然后才能在 DataGridRow 上设置任何属性

By container i meant DataGridRow in case of DataGrid. You need to modify your code like this:

我所说的容器是指 DataGrid 中的 DataGridRow。你需要像这样修改你的代码:

var dataGrid = new DataGrid();
dataGrid.ItemsSource = BuildDataGrid();
dataGrid.ItemContainerGenerator.StatusChanged += (s, e) =>
    {
       if (dataGrid.ItemContainerGenerator.Status == 
                           GeneratorStatus.ContainersGenerated)
       {
          var row = (DataGridRow)dataGrid.ItemContainerGenerator
                                               .ContainerFromIndex(0);
          row.Background = Brushes.Red;
       }
    };