WPF - How to get a cell from a DataGridRow?

前端 未结 2 1429
南笙
南笙 2021-02-08 07:54

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

2条回答
  •  被撕碎了的回忆
    2021-02-08 08:06

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

提交回复
热议问题