I have a data-bound DataGrid with alternating row background colors. I would like to color a cell differently based on the data it contains. I have tried the solution suggested
If you know your row and index of the cell you'd like to access, then here's how you can do it in code:
//here's usage
var cell = myDataGrid.GetCell(row, columnIndex);
if(cell != null)
cell.Background = Brushes.Green;
DataGrid Extension:
public static class DataGridExtensions
{
public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int columnIndex = 0)
{
if (row == null) return null;
var presenter = row.FindVisualChild();
if (presenter == null) return null;
var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (cell != null) return cell;
// now try to bring into view and retreive the cell
grid.ScrollIntoView(row, grid.Columns[columnIndex]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
return cell;
}