问题
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