【发布时间】:2023-08-26 17:28:01
【问题描述】:
我目前正在开发一个应用程序,该应用程序显示我从数据库查询到 DataGrid 的数据。
由于表格的列不知道高级,我无法将 DataGrid 实现为对象的 ObservableCollection,因此 DataGrid 绑定到 DataTable:
MyDataGrid.ItemsSource = _myDataTable.DefaultView;
用户应该能够直接在 DataGrid 中编辑数据,并且应该突出显示已编辑的单元格。
目前,我能在这件事上取得的唯一进展是使用CellEditEnding 事件来更改单元格的颜色:
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;
}
如果用户通过双击单元格、更改值并按 Enter 提交更改来编辑单元格,则此方法效果很好。
但是,如果用户编辑单元格并通过单击新行提交编辑,则会失败。在这种情况下,新单元格是着色的,而不是编辑过的单元格,这是有道理的,因为 dg.CurrentCell 会计算新选定的单元格。
哪些可能导致编辑的单元格而不是新选择的单元格着色?
您知道从绑定到 DataTable 的 DataGrid 中突出显示已编辑单元格的更好方法吗?
【问题讨论】:
-
我刚刚尝试了那个链接,但它似乎不起作用,但我会看看我是否能从该作者那里找到与我的特定用例相关的资源。