问题介绍
当ObservableCollection列表被UI线程占用时,如果在异步线程中调用ObservableCollection,会弹出以下异常:
问题分析
我们使用一个viewModel,在ViewModel中添加ObservableCollection类型的ItemsSource列表。
在列表使用ListBox绑定ItemsSource列表。再由界面触发对ItemsSource的修改。
1 public class ViewModel : INotifyPropertyChanged 2 { 3 private ObservableCollection<string> _itemsSource = new ObservableCollection<string>(); 4 5 public ObservableCollection<string> ItemsSource 6 { 7 get => _itemsSource; 8 set 9 { 10 _itemsSource = value; 11 OnPropertyChanged(); 12 } 13 } 14 15 public event PropertyChangedEventHandler PropertyChanged; 16 17 [NotifyPropertyChangedInvocator] 18 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 19 { 20 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 21 } 22 }