How to Copy List in Observable Collection in Thread

元气小坏坏 提交于 2019-12-12 04:07:48

问题


I have a background worker who fills/refills a List and After refilling and editing the List I copy this list in an Observable List:

this.OBSMailCountList = new ObservableCollection<IMailCount>(_allMailCounts);

The Problem is that the Collection is bind to an Live Diagramm and after the Copy in the List I get the

Error:

"The Value can not be NULL".

My Question is:

How to Copy an Observable Collection with Bindings in a Thread ?


回答1:


Your problem is that you have _allMailCounts == null at the moment you call observable collection constructor. You can check for null like this

if(_allMailCounts != null)
    OBSMailCountList = new ObservableCollection<IMailCount>(_allMailCounts);

Below is the answer on question "how to work with ObservableCollection from another tread":


Bind to observable collection defined as usual

ObservableCollection<IMailCount> _collection = new ObservableCollection<IMailCount>();
public ObservableCollection<IMailCount> Collection
{
    get { return _collection; }
    set
    {
        _collection = value;
        OnPropertyChanged();
    }
}

In another thread do work in this manner:

// create a copy as list in UI thread
List<IMailCount> collection = null;
Dispatcher.Invoke(() => collection = new List<IMailCount>(_collection));

// when finished working set property in UI thread
Dispatcher.InvokeAsync(() => Collection = new ObservableCollection<IMailCount>(collection));



回答2:


Dispatcher.Invoke( Action ) will be used to make the call to the UI thread.

Dispatcher.Invoke(() =>
{
      // Set property or change UI compomponents.           
      OBSMailCountList = new ObservableCollection<IMailCount>(_allMailCounts);   
}); 


来源:https://stackoverflow.com/questions/36153918/how-to-copy-list-in-observable-collection-in-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!