【WPF】当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素

问题:

  • 中文版报错:Additional information: 当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素。
  • 英文版报错:Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

原因:前台XAML中ListBox之类的含多个条目的控件,它的ItemsSource绑定了ViewModel中的某个ObservableCollection< T >集合,但在Model中调用时尝试访问这个控件,并修改它的ItemsSource。如下面的写法会报错:

<ListBox x:Name="designViewLB" ItemsSource="{Binding DesignViewList}">
shellWindow.designViewLB.Items.Add(new DesignViewItem() {
// ... 设置属性
});

解决:因为前台控件的ItemsSource已被绑定到某个集合中,所以不能再直接操作这个控件的ItemsSource,而应转为操作这个控件ItemsSource所绑定的集合。改为如下写法即可:

shellViewModel.DesignViewList.Add(new DesignViewItem()
{
// ... 设置属性
});
上一篇:三步解决fiddler升级后https无法通过证书验证问题


下一篇:rem的计算