Change a DataGridCell's background from the codebehind in Silverlight 4

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?


如果你循环了你的ItemsSource所绑定的集合,那么你可以获取每一行,并通过获取内容和单元格的列 - 像这样(技巧是content.Parent作为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 
    }
  }
}

此代码可用于更改单元格的颜色。

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


                }                  

            }
        }
    } 
链接地址: http://www.djcxy.com/p/71118.html

上一篇: 如何编辑绑定的DataGrid中的未绑定单元格?

下一篇: 从Silverlight 4中的代码隐藏中更改DataGridCell的背景