2013-08-22 624 views
0

我想标记某个数据网格的某些单元格以更改标记单元格的颜色。我可以与他们进行单细胞做这个代码:更改标记单元格的颜色

public static DataGridRow GetRow(this DataGrid dataGrid, int index) 
    { 
     DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index); 
     if (row == null) 
     { 
      dataGrid.UpdateLayout(); 
      dataGrid.ScrollIntoView(dataGrid.Items[index]); 
      row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index); 
     } 
     return row; 
    } 

    public static int GetRowIdx(this DataGrid dataGrid, DataGridCellInfo cellInfo) 
    { 
     // Use reflection to get DataGridCell.RowDataItem property value. 
     DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item); 
     if (row == null) 
      throw new NullReferenceException("Fehler: Keine Index gefunden da DataGridRow null!"); 
     return row.GetIndex(); 
    } 



    public static DataGridCell GetCurrentCell(this DataGrid dataGrid) 
    { 
     int row = GetRowIdx(dataGrid, dataGrid.CurrentCell); 
     int column = dataGrid.CurrentColumn.DisplayIndex; 

     return GetCell(dataGrid, row, column); 
    } 

调用:

DataGridCell currentCell = DataGridExtension.GetCurrentCell(dataGrid1); 
    currentCell.Background = Brushes.LightGray; 

有人知道如何更改此代码,这样我可以标记例如5个细胞并改变它们的颜色?

回答

1

您可以创建DataGridCell的集合,并将其标记都在另一个事件,如单击一个按钮:

List<DataGridCell> CellList = new List<DataGridCell>(); 

然后,每当你在一个单元格单击使该事件的细胞添加到CellList:

DataGridCell currentCell = DataGridExtension.GetCurrentCell(dataGrid1); 
CellList.Add(currentCell); 

然后,当你想要的所有单元格更改为新的颜色,请单击一个按钮,将其添加到事件处理程序:

foreach (DataGridCell cell in CellList) 
{ 
    cell.Background = Brushes.LightGray; 
}