Reputation: 3
I am currently working on an app displaying data I am querying from a database into a DataGrid.
As the columns of the table are not know in advanced, I was not able to implement the DataGrid as an ObservableCollection of objects, and the DataGrid is consequently binded to a DataTable:
MyDataGrid.ItemsSource = _myDataTable.DefaultView;
Users should be able to edit data directly in the DataGrid, and the edited cells should be highlighted.
At the moment, the only progress I was able to make on that matter was to use the CellEditEnding
event to change the color of the cell:
private void MyDataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
DataGridCell gridCell = null;
if (sender is DataGrid dg)
{
gridCell = GetCell(dg.CurrentCell);
}
if (gridCell != null)
gridCell.Foreground = Brushes.Red;
}
}
public DataGridCell GetCell(DataGridCellInfo dataGridCellInfo)
{
if (!dataGridCellInfo.IsValid)
{
return null;
}
var cellContent = dataGridCellInfo.Column.GetCellContent(dataGridCellInfo.Item);
return (DataGridCell) cellContent?.Parent;
}
This approach works well if a user edits a cell by double-clicking on it, changing the value and pressing enter to commit the changes.
However, it fails if the user edits the cell and commits the editing by clicking on a new row. In this case, the new cell is colored rather than the edited one, which makes sense as dg.CurrentCell
evaluates to the new selected cell.
What are possible leads to color the edited cell rather than the newly selected cell?
Do you know of a better approach to highlight edited cells from a DataGrid bonded to a DataTable?
Upvotes: 0
Views: 1269
Reputation: 1521
Like you said, using the CurrentCell won't work because it changes when selecting a different cell. The OnCellEditEnding event provides the edited element in the event arguments but you need to get the DataGridCell that it is contained in to change cell properties. I too wish it would just be provided but you need to walk up the visual tree to get it:
private void MyDataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
DependencyObject depObj = e.EditingElement;
while (depObj != null && !(depObj is DataGridCell)) {
depObj = VisualTreeHelper.GetParent (depObj);
}
if (depObj != null) {
DataGridCell gridCell = (DataGridCell) depObj;
gridCell.Foreground = Brushes.Red;
}
}
}
Upvotes: 2