What's the best way to update an ObservableCollection from another thread?

后端 未结 5 980
终归单人心
终归单人心 2020-12-23 17:06

I am using the BackgroundWorker to update an ObservableCollection but it gives this error:

\"This type of CollectionVi

5条回答
  •  臣服心动
    2020-12-23 17:48

    If MVVM

    public class MainWindowViewModel : ViewModel {
    
        private ICommand loadcommand;
        public ICommand LoadCommand { get { return loadcommand ?? (loadcommand = new RelayCommand(param => Load())); } }
    
        private ObservableCollection items;
        public ObservableCollection Items {
            get {
                if (items == null) {
                    items = new ObservableCollection();
                }
                return items;
            }
        }
    
        public void Load() {
            BackgroundWorker bgworker = new BackgroundWorker();
            bgworker.WorkerReportsProgress = true;
            bgworker.DoWork += (s, e) => {
                for(int i=0; i<10; i++) {
                    System.Threading.Thread.Sleep(1000);
                    bgworker.ReportProgress(i, new List());
                }
                e.Result = null;
            };
            bgworker.ProgressChanged += (s, e) => {
                List partialresult = (List)e.UserState;
                partialresult.ForEach(i => {
                    Items.Add(i);
                });
            };
            bgworker.RunWorkerCompleted += (s, e) => {
                //do anything here
            };
            bgworker.RunWorkerAsync();
        }
    }
    

提交回复
热议问题