C# 突出显示WPF DataGrid的已编辑单元格
我目前正在开发一个应用程序,该应用程序显示我正在从数据库向DataGrid查询的数据 由于表的列在advanced中是未知的,我无法将DataGrid实现为对象的ObservableCollection,因此DataGrid绑定到DataTable:C# 突出显示WPF DataGrid的已编辑单元格,c#,wpf,datagrid,C#,Wpf,Datagrid,我目前正在开发一个应用程序,该应用程序显示我正在从数据库向DataGrid查询的数据 由于表的列在advanced中是未知的,我无法将DataGrid实现为对象的ObservableCollection,因此DataGrid绑定到DataTable: MyDataGrid.ItemsSource = _myDataTable.DefaultView; 用户应该能够直接在DataGrid中编辑数据,并且编辑的单元格应该高亮显示 目前,我能在这方面取得的唯一进展是使用CellEditEnding事
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中编辑的单元格吗?正如您所说,使用CurrentCell将不起作用,因为它在选择其他单元格时会发生变化。OnCelledEnding事件在事件参数中提供已编辑的元素,但您需要获取包含该元素的DataGridCell才能更改单元格属性。我也希望它能被提供,但你需要走上视觉树才能得到它:
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;
}
}
}
正如您所说,使用CurrentCell将不起作用,因为它在选择其他单元格时会发生变化。OnCelledEnding事件在事件参数中提供已编辑的元素,但您需要获取包含该元素的DataGridCell才能更改单元格属性。我也希望它能被提供,但你需要走上视觉树才能得到它:
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;
}
}
}
查看此链接:我刚刚尝试了该链接,但它似乎不起作用,但我将查看是否从该作者处找到与我的特定用例相关的资源。查看此链接:我刚刚尝试了该链接,但它似乎不起作用,但我将查看是否从该作者处找到与我的特定用例相关的资源。