Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

I create a DataGrid object in my code behind and set the content with 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 DataGrid object in the code behind like following:

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 row object is null. Why is that?

like image 257
John Threepwood Avatar asked Mar 05 '14 18:03

John Threepwood


1 Answers

You can get the DataGridRow using ItemContainerGenerator of dataGrid.

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

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

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

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.

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

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;
       }
    };
like image 136
Rohit Vats Avatar answered Oct 05 '22 23:10

Rohit Vats