简体   繁体   中英

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: 在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM