突出显示WPF DataGrid的已编辑单元格

时间:2018-09-20 09:14:01

标签: c# wpf datagrid

我目前正在开发一个应用程序,用于显示我正在从数据库查询到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中的已编辑单元格吗?

1 个答案:

答案 0 :(得分:1)

就像您说的那样,使用CurrentCell无效,因为在选择其他单元格时它会更改。 OnCellEditEnding事件在事件参数中提供了已编辑的元素,但是您需要获取其中包含的DataGridCell才能更改单元格属性。我也希望只提供它,但是您需要走到视觉树上才能获得它:

import { map } from 'rxjs/operators';
相关问题