> 文档中心 > C#报错System.InvalidOperationException:“当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素。”

C#报错System.InvalidOperationException:“当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素。”

C#处理DataGrid的时候偶然遇到以下报错信息:

System.InvalidOperationException:“当 ItemsSource 正在使用时操作无效。改用
ItemsControl.ItemsSource 访问和修改元素。”

这是因为DataGrid中使用了Binding了一个List对象,而后在代码却又使用另一种方式去操作DataGrid,如使用

DataGrid.Items.Remove(selectRow);

去操作数据,这必然会导致ItemSource出现改变,而与Binding的对象产生冲突,所以类似报错:
C#报错System.InvalidOperationException:“当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素。”

解决:

统一先用List去操作数据,之后再给DataGrid的ItemsSource重新赋值,如:

DataGrid.ItemsSource = list;

或者是使用Binding的List去操作数据,然后利用OnPropertyChanged(“list”)去同步更新表格,如:

 <DataGrid Height="200" ItemsSource="{Binding Model.Data.ShowInstrumentList,UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False" AutoGenerateColumns="False">
 private List<Instrument> showInstrumentList; public List<Instrument> ShowInstrumentList {     get     {  return showInstrumentList;     }     set     {  showInstrumentList = value;  OnPropertyChanged("ShowInstrumentList");     } }

然后操作list的数据,就会同步到DataGrid中了。