Reputation: 1332
I want to mark some cells of a datagrid to change the color of the marked cells. I can do this with them code for a single cell:
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);
}
the calling:
DataGridCell currentCell = DataGridExtension.GetCurrentCell(dataGrid1);
currentCell.Background = Brushes.LightGray;
Someone know how to change this code, so that i can mark for example 5 cells and change their color?
Upvotes: 0
Views: 140
Reputation: 2043
You could create a collection of DataGridCell's and mark them all on another event, like clicking a button:
List<DataGridCell> CellList = new List<DataGridCell>();
Then whenever you click on a cell make that event add the cell to the CellList:
DataGridCell currentCell = DataGridExtension.GetCurrentCell(dataGrid1);
CellList.Add(currentCell);
Then when you want to change all the cells to the new color, click on a button and add this to the event handler:
foreach (DataGridCell cell in CellList)
{
cell.Background = Brushes.LightGray;
}
Upvotes: 1