INotifyCollectionChanged のカスタム実装で CollectionChanged イベントをトリガーすると、この例外が発生します。
タイプ '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);
ありがとう!