John Threepwood
John Threepwood

Reputation: 16143

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

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?

Upvotes: 5

Views: 13454

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81313

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;
       }
    };

Upvotes: 12

Related Questions