2013-08-22 514 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; 
}