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

WPF中DialogBox按钮命令执行后DataGrid不更新的问题求助

问题分析与解决方案

核心问题

你代码里的RaiseProperChanged()(应该是RaisePropertyChanged()的笔误)未指定具体属性名,导致WPF绑定系统无法感知customerCollection的更新。切换页面能正常显示是因为页面重新加载时会重新触发绑定,而弹窗关闭后的GetData()虽然重新获取了数据,但没正确通知UI更新。

具体修复步骤

1. 修正属性变更通知调用

在GetData()方法中,明确触发customerCollection的属性变更通知,替换无参的RaiseProperChanged():

protected void GetData()
{
    customer = customerRepository.GetByAll();
    customerCollection = CollectionViewSource.GetDefaultView(customer);
    customerCollection.Filter = FilterByName;
    customerCollection.Refresh();
    RaisePropertyChanged(nameof(customerCollection)); // 指定属性名触发通知
}

如果你的ViewModel基类的RaisePropertyChanged不支持参数,需要补充标准实现:

public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

2. 优化ObservableCollection使用(可选)

如果customerRepository.GetByAll()返回的是普通List而非ObservableCollection,可复用原有集合实例减少内存分配:

protected void GetData()
{
    var newCustomers = customerRepository.GetByAll().ToList();
    customer.Clear();
    foreach (var cust in newCustomers)
    {
        customer.Add(cust);
    }
    customerCollection = CollectionViewSource.GetDefaultView(customer);
    customerCollection.Filter = FilterByName;
    customerCollection.Refresh();
    RaisePropertyChanged(nameof(customerCollection));
}

前提是customer已作为ViewModel成员变量提前初始化。

3. 优化弹窗与主ViewModel的交互(解耦)

当前弹窗ViewModel直接调用GetData()不符合MVVM解耦原则,可通过事件通知主ViewModel刷新:

  • 在弹窗ViewModel中定义事件:
// AddNewCustomerViewModel内
public event Action OnCustomerSaved;

private void ExecuteSaveCustomerCommand(object obj)
{
    customerModel.FirstName = FirstName;
    customerModel.LastName = LastName;
    customerModel.Contact = Contact;
    customerModel.Address = Address;
    customerRepository.Add(customerModel);
    OnCustomerSaved?.Invoke();
    CloseAction();
}
  • 在主ViewModel的弹窗显示命令中订阅事件:
private void ExecuteShowNewCustomerWindowCommand(object obj)
{
    var vm = new AddNewCustomerViewModel();
    vm.OnCustomerSaved += () => GetData();
    var addNewCustomer = new AddNewCustomer { DataContext = vm };
    addNewCustomer.ShowDialog();
}

验证要点

  • 确认customerCollection是ViewModel的公共属性,且DataGrid的ItemsSource绑定正确:
    <DataGrid ItemsSource="{Binding customerCollection}" ... />
    
  • 检查ViewModel基类的INotifyPropertyChanged实现是否正常,确保属性变更能被WPF捕获。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:31:05