I hope I can reject some elements after adding them to the ObservableCollection. I cannot subclass ObservableCollection or use any kind, so I seem to be limited to using one event handler (CollectionChanged) to execute .Remove () on forbidden elements. It is good if the elements exist for a short period between the event raised and processed; items should simply not be stored in the collection. Calling .Remove () inside the CollectionChanged event handler does not seem valid. When starting, .NET throws an InvalidOperationException:
"Cannot change ObservableCollection during CollectionChanged event."
Personally, I believe that .NET should let me do this. If I create an infinite loop, this is my own mistake.
The code I would like to use would look like this:
myCollection.CollectionChanged += (sender, args) => { if (args.Action == NotifyCollectionChangedAction.Remove) return; foreach (var itm in myCollection) { if (itm.name == "Fred") myCollection.Remove(itm); } }
I'm not sure what my options are. Using dispatcher does not work. Triggering another event and placing the .Remove call in another handler is the only other option that comes to mind.
ebpa
source share