问题
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 !
}
}
}
}
回答1:
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.
来源:https://stackoverflow.com/questions/26794217/prevent-adding-the-new-item-on-observablecollection-collectionchanged-event