上自定義實現INotifyCollectionChanged的觸發CollectionChanged事件,當我得到這個異常:System.InvalidOperationException「否」集合更改事件指標不適用於大小的集合「0」
例外「System.InvalidOperationException」類型的出現在 PresentationFramework.dll但在用戶代碼中沒有處理
附加信息:「25」集合更改事件索引不 有效大小的集合「0」。
XAML Datagrid作爲ItemsSource綁定到集合。
如何避免此異常?
的代碼如下:在下面的行發生
public class MultiThreadObservableCollection<T> : ObservableCollection<T>
{
private readonly object lockObject;
public MultiThreadObservableCollection()
{
lockObject = new object();
}
private NotifyCollectionChangedEventHandler myPropertyChangedDelegate;
public override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
lock (this.lockObject)
{
myPropertyChangedDelegate += value;
}
}
remove
{
lock (this.lockObject)
{
myPropertyChangedDelegate -= value;
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var eh = this.myPropertyChangedDelegate;
if (eh != null)
{
Dispatcher dispatcher;
lock (this.lockObject)
{
dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
let dpo = nh.Target as DispatcherObject
where dpo != null
select dpo.Dispatcher).FirstOrDefault();
}
if (dispatcher != null && dispatcher.CheckAccess() == false)
{
dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => this.OnCollectionChanged(e)));
}
else
{
lock (this.lockObject)
{
foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
{
nh.Invoke(this, e);
}
}
}
}
}
錯誤:
nh.Invoke(this, e);
謝謝!