WPF DataGrid调用Entity Framework SaveChanges()后未实时更新问题
问题根源与解决方案
核心原因
DataGrid无法实时更新Count值,是因为你的Product实体没有实现**INotifyPropertyChanged接口**。EF的DbSet.Local是ObservableCollection<T>,它只会监听集合的增删变更,但不会自动处理实体内部属性的变更通知——只有当实体本身触发属性变更事件时,UI才能实时刷新显示最新值。
另外你的Window_Closing方法里有笔误:_input.Dispose()应该是_context.Dispose(),否则数据库上下文无法正确释放资源。
具体修复步骤
1. 修改Product实体,实现属性变更通知
using System.ComponentModel; using System.Runtime.CompilerServices; public class Product : INotifyPropertyChanged { private string _id; private int _count; public string Id { get => _id; set { if (_id != value) { _id = value; OnPropertyChanged(); } } } public int Count { get => _count; set { if (_count != value) { _count = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
2. 修正Window_Closing的资源释放代码
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { _context?.Dispose(); }
可选优化与建议
- 异步操作优化:将数据库操作改为异步,避免阻塞UI线程:
private async void Button_Click(object sender, RoutedEventArgs e) { var productId = idTextBox.Text.Trim(); if (string.IsNullOrEmpty(productId)) return; // 空ID输入验证 Product oldProduct = await _context.Products.FindAsync(productId); if(oldProduct != null) oldProduct.Count++; else _context.Products.Add(new Product { Id = productId, Count = 1 }); await _context.SaveChangesAsync(); } - 输入验证:添加对
idTextBox的非空/格式验证,避免无效数据存入数据库。 - 绑定优化:可以在DataGrid的绑定中显式指定
UpdateSourceTrigger=PropertyChanged(不过本次问题核心是实体通知,此步为可选):<DataGridTextColumn Header="COUNT" Binding="{Binding Count, UpdateSourceTrigger=PropertyChanged}"/>
内容的提问来源于stack exchange,提问作者UltraMurlock
相关产品推荐
相关产品推荐

