WPF - How to get a cell from a DataGridRow?

maayaa picture maayaa · Sep 8, 2010 · Viewed 20.5k times · Source

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 by this thread

http://wpf.codeplex.com/Thread/View.aspx?ThreadId=51143

But,

DataGridCellsPresenter presenter = GetVisualChild(row)

always returns null.

I am using

    public static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }

But VisualTreeHelper.GetChildrenCount() of a DataGridRow always returns 0. I have verified that DataGridRow is not null and has been populated with data already. Any help is appreciated.

Thanks.

Answer

denis morozov picture denis morozov · Jan 22, 2014

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<DataGridCellsPresenter>();
        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;
    }