WPF DataGrid CellEditEnding事件无法更新EF7数据的问题求助
解决WPF DataGrid编辑后EF7无法保存的问题
问题根源
CellEditEnding事件的触发时机是编辑操作即将提交但还未同步到绑定的数据源,此时调用SaveChanges(),EF上下文还未获取到新值,因此无法更新数据库。
解决方案1:用Dispatcher延迟执行保存
把保存操作放到UI线程的下一个执行周期,确保数据源完成同步后再执行:
private void DataGrid_CellEditEnding(object sender, System.Windows.Controls.DataGridCellEditEndingEventArgs e) { if (e.EditAction == System.Windows.Controls.DataGridEditAction.Commit) { // 延迟到UI线程下一轮执行,保证数据源已更新 Application.Current.Dispatcher.BeginInvoke(() => { App.DBContext.SaveChanges(); }); } }
解决方案2:手动同步编辑值到数据源
直接从编辑控件提取新值,手动赋值给绑定的实体后再保存:
private void DataGrid_CellEditEnding(object sender, System.Windows.Controls.DataGridCellEditEndingEventArgs e) { if (e.EditAction == System.Windows.Controls.DataGridEditAction.Commit) { // 获取当前编辑的实体对象 var targetEntity = e.Row.Item as YourEntityClass; if (targetEntity == null) return; // 获取编辑控件(以TextBox为例,根据实际控件类型调整) var editBox = e.EditingElement as TextBox; if (editBox == null) return; // 获取当前列绑定的属性名 var boundColumn = e.Column as System.Windows.Controls.DataGridBoundColumn; var bindingPath = (boundColumn?.Binding as System.Windows.Data.Binding)?.Path.Path; if (string.IsNullOrEmpty(bindingPath)) return; // 手动将控件值赋值给实体属性(需根据属性类型处理类型转换) var property = targetEntity.GetType().GetProperty(bindingPath); if (property != null) { var newValue = Convert.ChangeType(editBox.Text, property.PropertyType); property.SetValue(targetEntity, newValue); } App.DBContext.SaveChanges(); } }
解决方案3:改用RowEditEnding事件
如果是整行编辑完成后保存,RowEditEnding事件的触发时机更靠后,此时数据源已完成同步:
private void DataGrid_RowEditEnding(object sender, System.Windows.Controls.DataGridRowEditEndingEventArgs e) { if (e.EditAction == System.Windows.Controls.DataGridEditAction.Commit) { App.DBContext.SaveChanges(); } }
额外提示
- 确保你的实体类实现了
INotifyPropertyChanged接口,保证数据绑定能正确同步值到EF上下文。 - 若未使用EF7的跟踪代理,需手动标记实体状态:
App.DBContext.Entry(targetEntity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
内容的提问来源于stack exchange,提问作者Loyvsc
相关产品推荐
相关产品推荐

