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

WPF DataGrid删除行报错:Operation is not valid while ItemsSource is in use

解决WPF DataGrid删除行时的"ItemsSource is in use"异常

嘿,这个问题我太熟悉了!你碰到的这个异常其实是WPF的一种保护机制——当你给DataGrid绑定了ItemsSource之后,绝对不能直接去修改DataGrid的Items集合,必须操作绑定的原始数据源才行。

为什么会报错?

Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead

这个提示已经把原因说透了:当DataGrid的ItemsSource指向一个集合(比如List、ObservableCollection)时,控件的Items是完全由这个数据源驱动的。直接修改Items会破坏绑定的一致性,所以WPF会直接抛出异常阻止你这么做。

修复方案

核心思路就是:修改绑定的数据源,而不是DataGrid控件本身的Items集合

1. 确保用ObservableCollection作为数据源(关键!)

如果还没这么做,赶紧把你的数据源换成ObservableCollection<T>——它实现了INotifyCollectionChanged接口,修改集合时会自动通知UI更新,这是WPF数据绑定的最佳实践。

比如在你的窗口类里定义数据源:

// 替换成你的实际数据模型类型
public ObservableCollection<YourDataModel> GridDataSource { get; set; }

public YourWindow()
{
    InitializeComponent();
    // 初始化数据源并绑定到DataGrid
    GridDataSource = new ObservableCollection<YourDataModel>();
    dataGrid.ItemsSource = GridDataSource;
}

2. 修改删除按钮的事件逻辑

直接从绑定的ObservableCollection里移除选中项,而不是操作dataGrid.Items:

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    // 把选中项转成你的数据模型类型,避免类型转换错误
    var selectedItem = dataGrid.SelectedItem as YourDataModel;
    if (selectedItem != null)
    {
        // 直接操作数据源
        GridDataSource.Remove(selectedItem);
    }
}

额外注意点

  • 如果你的数据源是普通的List<T>,即使删除了元素,UI也不会自动刷新——因为List没有通知UI变化的机制,所以一定要换成ObservableCollection<T>
  • 如果是用MVVM模式开发,建议把删除逻辑放到ViewModel里,通过ICommand绑定按钮,尽量避免在后台代码里直接操作控件(不过按照你当前的代码结构,上面的方案完全适用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:55:39