FoldFence
FoldFence

Reputation: 2802

How to Copy List in Observable Collection in Thread

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 ?

Upvotes: 0

Views: 269

Answers (2)

Sinatr
Sinatr

Reputation: 21999

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));

Upvotes: 1

Hari Prasad
Hari Prasad

Reputation: 16956

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);   
}); 

Upvotes: 1

Related Questions