Prevent adding the new Item on ObservableCollection.CollectionChanged event

℡╲_俬逩灬. 提交于 2019-12-11 02:53:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!