Changing Cell Color according to condition in IF in C # WPF source code

2

I have a DataGrid in a form in C # WPF, how can I execute a method retrieve each cell contained in that DataGrid and assign a possible value, or change the background color?

For example I have a DataGrid:

[ A ] [ D ] [ C ] [ C ]
[ B ] [ A ] [ B ] [ A ]
[ C ] [ A ] [ B ] [ D ]

And then I want to make a loop of repetition:

for (i<TamanhoDeLinhas) // Andar Linha
  for(j<TamanhodeColunas) // Andar Coluna
     if(DataGrid[i][j].Conteudo == A)
       DataGrid[i][j].BackGround = Color.Red;

Is it possible to do this?

Or, I have the corresponding values of I J, that is, I know in which position the values will be! I have to change the background of the cell in Line i = 2 and j = 3. How can you do that? Retrieve the cell and assign a new color according to your position or reading one by one?

The DataGrid in question is bound to a DataTable and it generates the columns and rows automatically, in case it is dynamic. so I do DataGrid.SourceItems = DataTable.DefaultView ... And so I play all the items for the DataGrid.

Either solution is valid.

    
asked by anonymous 29.05.2017 / 13:17

2 answers

3

If you know the indexes, I did this test:

public DataGridCell GetCell(DataGridCellInfo cellInfo)
{
  var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
  if (cellContent != null)
     return (DataGridCell)cellContent.Parent;
  return null;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  var cellInfo = new DataGridCellInfo(gd.Items[0], gd.Columns[2]);
  var cell = GetCell(cellInfo);
  cell.Background = Brushes.Red;
}

Understanding that, in the loaded window you have already assigned the values to your grid.

    
29.05.2017 / 14:30
2

Create an extension. For example, DataGridExtensions.cs :

public static class DataGridExtensions
{
    public static DataGridCell GetCell(this DataGrid grid,  DataGridRow linha, int indiceColuna = 0)
    {
        if (linha == null) return null;

        var presenter = linha.FindVisualChild<DataGridCellsPresenter>();
        if (presenter == null) return null;

        var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(indiceColuna);
        if (cell != null) return cell;

        grid.ScrollIntoView(linha, grid.Columns[indiceColuna]);
        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(indiceColuna);

        return cell;
    }
}

Retrieve cell:

var cell = meuDataGrid.GetCell(linha, indiceColuna);

Using the correct color type, both cases will work. WPF Background is of type System.Windows.Media.Brush .

Examples of use with the retrieved cell:

// using System.Windows.Media;

cell.Background = Brushes.White;
cell.Background = new SolidColorBrush(Color.White);
cell.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
cell.Background = System.Windows.SystemColors.MenuHighlightBrush;
    
29.05.2017 / 14:06