3

I need to check some conditions and then decide to add the new Item to my collection or not, is there anyway i can prevent adding in my CollectionChanged event or is it too late at the point? actually i can modify the new Item but can not remove it from the NewItems collection due to runtime exception:

    protected void MyFilter(object sender, NotifyCollectionChangedEventArgs e)
    {                   
         f (e.Action == NotifyCollectionChangedAction.Add)
         {
             foreach (Item item in e.NewItems)
             {
                 if (!Item.CanBeAdded())
                 {
                      //Prevent adding the Item !
                 }
             }             
        }
    }
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • Some frameworks have gotten around this by implementing a `INotifyCollectionChanging` interface. – Aron Nov 07 '14 at 09:13
  • Interesting question, quite similar to my own one [here](http://stackoverflow.com/questions/42528460/add-a-check-with-messagebox-when-datagrid-is-changed/)... do you have a more updated answer or what is the current status of this? –  Mar 01 '17 at 12:46

1 Answers1

0

Well the problem here is it's already added in the collection. The only way to do it if I follow this is removing it from the collection then. But that would retrigger the MyyFilter subscription you created.

If this collection is bound on a grid or anywhere where you can create an item from the UI, then i suggest you create a custom observable collection.

Basic code would be like this.

public class MyObservableCollection<T> : ICollection<T>
, INotifyCollectionChanged
, INotifyPropertyChanged
{
}

Implement your validation logic on the Add method of ICollection.

if you want to, just go ahead and copy this guys implementation.

riQQ
  • 9,878
  • 7
  • 49
  • 66
DevEstacion
  • 1,947
  • 1
  • 14
  • 28