Search code examples
c#wpfcolorsdatagridcell

How to colour a datagrid cell in code behind and when it is not visible


I have a function that acts on a datagrid on a peculiar row:

private void SetColour(int row)
{
    if (dtg_Ppdescr_Permanent.ItemContainerGenerator.ContainerFromItem(dtg_Ppdescr_Permanent.Items[row]) is DataGridRow dtgRowExecuting)
    {
        DataGridCell dtgCellExecuting0 = dtg_Ppdescr_Permanent.Columns[0].GetCellContent(dtgRowExecuting).Parent as DataGridCell;
        DataGridCell dtgCellExecuting1 = dtg_Ppdescr_Permanent.Columns[1].GetCellContent(dtgRowExecuting).Parent as DataGridCell;
        dtgRowExecuting.BringIntoView();
        switch (dtgRowExecuting.Tag.ToString())
        {
            case "ARM1":
                dtgCellExecuting0.Background = Helper.GetColour_Yellow();
                dtgCellExecuting0.Foreground = Helper.GetColour_Black(); break;
            case "ARM12":
                dtgCellExecuting0.Background = dtgCellExecuting1.Background = Helper.GetColour_Yellow();
                dtgCellExecuting0.Foreground = Helper.GetColour_Red();
                break;
            case "ARM2":
                dtgCellExecuting1.Background = dtgCellExecuting1.Background = Helper.GetColour_Yellow();
                dtgCellExecuting1.Foreground = Helper.GetColour_Green();
                break;
        }
    }
}

and that works properly as in the picture: enter image description here

the datagrid is in a tabItem. The only problem is that to make the colourization work the tabItem has to be selected and so the datagrid has to be visible. If it isn't the colourization has no effect. Is there any way to change it and make it work? What is wrong in my code? Thanks in advance Patrick


Solution

  • I have found the solution: I can operate through the datagridLoad.LoadingRow event. For the sake of knowloedge this is how to do it:

    datagrid.LoadingRow += (sender, args) =>
    {
        int rowNum = args.Row.GetIndex();
        DataGridRow row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(rowNum);
        if (row != null)
            row.Background = Brushes.Pink;
    }