You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGrid按下Enter键保存时SelectedItem数据未更新问题求助

解决WPF DataGrid按下Enter时未同步编辑内容到数据源的问题

这问题我之前也碰到过!核心原因是WPF DataGrid的默认行为:当你在单元格里编辑内容时,只有当单元格失去焦点(比如点别的单元格),编辑的值才会真正提交到绑定的数据源对象里。你按下Enter的时候,当前单元格还处于编辑状态,所以SelectedItem拿到的还是修改前的旧数据。

解决方法很简单,在你获取SelectedItem之前,先强制提交当前的编辑操作,把值同步到数据源。直接修改你的KeyDown方法就行:

private void dataGrid_KeyDown(object sender, KeyEventArgs e) {
    if(e.Key == Key.Enter) {
        // 先提交当前单元格和行的编辑,确保值同步到数据源
        if (dataGrid.IsEditing) {
            // 提交单元格级别的编辑,true表示强制提交
            dataGrid.CommitEdit(DataGridEditingUnit.Cell, true);
            // 提交行级别的编辑,确保整行的修改都同步
            dataGrid.CommitEdit(DataGridEditingUnit.Row, true);
        }

        var wasError = false;
        LibraryRecord item = null;
        try {
            item = (LibraryRecord)dataGrid.SelectedItem;
        } catch(Exception a) {
            wasError = true;
            MessageBox.Show("Cannot insert on last line.", "Error");
            dataGrid.SelectedIndex = dataGrid.Items.Count - 2;
        }
        if (!wasError && item != null) {
            using (var context = new LibraryEntities()) {
                try {
                    var record = context.LibraryRecords.FirstOrDefault(q => q.ID == item.ID);
                    // 加个空判断,避免找不到对应记录时抛出异常
                    if (record != null) {
                        record.Date = item.Date;
                        record.Description = item.Description;
                        record.Name = item.Name;
                        record.NegNumber = item.NegNumber;
                        record.BoxNumber = item.BoxNumber;
                        context.SaveChanges();
                    }
                } catch (Exception a) {
                    MessageBox.Show("System Message:\n" + a.Message, "ERROR");
                }
            }
            // 自动跳转到下一行,并且可选进入编辑状态
            if (dataGrid.SelectedIndex < dataGrid.Items.Count - 1) {
                dataGrid.SelectedIndex++;
                // 定位到下一行的第一个单元格并开始编辑
                dataGrid.CurrentCell = new DataGridCellInfo(dataGrid.Items[dataGrid.SelectedIndex], dataGrid.Columns[0]);
                dataGrid.BeginEdit();
            }
        }
    }
}

额外补充的几个细节:

  • CommitEdit方法的第二个参数传true,表示强制提交编辑,哪怕内容不符合验证规则(如果有验证的话),你也可以根据需求改成false。
  • 我加了item != null和record != null的空判断,避免代码因为意外情况抛出空引用异常,让程序更稳定。
  • 最后补了自动跳转到下一行并进入编辑状态的代码,刚好匹配你想要的“自动跳转到下一行”的需求。
  • 另外建议你的LibraryRecord类实现INotifyPropertyChanged接口,这样双向绑定的同步会更顺畅,虽然这不是当前问题的直接原因,但对DataGrid的整体使用体验很重要。

内容的提问来源于stack exchange,提问作者mackentish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:07:33