Question

I'm trying to implement a collection class (either derived from ObservableCollection or BindingList) that will allow me to cancel the addition of any new item as it happens.

Now I know ObservableCollection does not allow the editing of items in the collection during the CollectionChanged event for a reason but I'm looking for a way to 'bypass' this either by deriving from ObservableCollection or BindingList.

Any examples will be appreciated.

Was it helpful?

Solution

Well, you would need some BeforeCollectionChanged event, pass an EventArgs with a Cancelled property which you look at to determine whether to add it or not.

Kinda like this, I guess:

public override void Add(T item) {
  var e = new BeforeCollectionChangedEventArgs();
  RaiseBeforeCollectionChanged(e);
  if (!e.Canceled)
    base.Add(item);
}

CollectionChanged is obviously too late because by then the collection already has been changed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top