我想标记数据网格的某些单元格以更改标记单元格的颜色。我可以使用它们为单个单元格编写代码:
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个单元格并更改其颜色吗?
答案 0 :(得分: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;
}