问题介绍

当ObservableCollection列表被UI线程占用时,如果在异步线程中调用ObservableCollection,会弹出以下异常:

WPF 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     }
View Code

相关文章:

  • 2021-09-15
  • 2022-12-23
  • 2021-04-28
  • 2021-11-07
  • 2021-09-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-10
  • 2021-06-21
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案