Question

I am writing a silverlight app that lets you parse copied text via entered delimiters. After the data is parsed and dropped into the grid, the user has the ability to "Scrub" the data. This compares the current value of a cell to the allowed values for the column, picks its best guess and rebinds the data to the grid via the ItemsSource property.

My problem is that I know the coordinates of each cell that has been "Scrubbed", and I would like to highlight this cell or change its background color. As far as I can see, you can set a DataGridCell's background individually, but I have no way to access the DataGridCell. I have access to the Grid's columns and rows, but these also do not appear to give access to the DataGridCell as I had hoped. Does anyone have a way to access a DataGridCell after the ItemsSource has been set?

Was it helpful?

Solution

If you loop through the collection your ItemsSource is bound to, you can then take each row and go through the columns getting the content and cell - something like this (trick is the content.Parent as DataGridCell):

var collection = grid.ItemsSource;
foreach (var dataItem in collection)
{
  foreach (var col in grid.Columns)
  {
    var content = col.GetCellContent(dataItem);
    if (content != null)
    {
        DataGridCell cell = content.Parent as DataGridCell;
        // do whatever you need to do with the cell like setting cell.Background 
    }
  }
}

OTHER TIPS

This code is useful to change the color of the cell.

void datagrid_LoadingRow()
    {

        var collection = datagrid.ItemsSource;
        foreach (var dataItem in collection)
        {
            foreach (var col in datagrid.Columns)
            {
                var content1 = col.GetCellContent(dataItem);
                if (content1 != null)
                {
                    TextBlock block = content1 as TextBlock;
                    if (block != null)
                    {
                        DataGridCell cell = content1.Parent as DataGridCell;

                        string cellText = block.Text;
                        if (cellText == "True")
                        {
                            cell.Background = new SolidColorBrush(Colors.Green);
                        }
                        if (cellText == "False")
                        {
                            cell.Background = new SolidColorBrush(Colors.Red);
                        }                            
                    }


                }                  

            }
        }
    } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top