CollectionChanged事件上添加新项目

CollectionChanged事件上添加新项目

本文介绍了防止在ObservableCollection.CollectionChanged事件上添加新项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一些条件,然后决定是否将新Item添加到我的收藏夹中,是否可以阻止我添加CollectionChanged事件,或者现在是否为时已晚?实际上,我可以修改新项目,但由于运行时异常而无法将其从NewItems集合中删除:

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 !
                 }
             }
        }
    }

推荐答案

这里的问题是它已添加到集合中.如果执行此操作的唯一方法是从集合中删除它.但这会重新触发您创建的MyyFilter订阅.

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.

如果此集合绑定在网格上或可以从UI创建项目的任何地方,那么我建议您创建一个自定义的可观察集合.

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.

基本代码就是这样.

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

在ICollection的Add方法上实施验证逻辑.

Implement your validation logic on the Add method of ICollection.

如果愿意,请继续复制此家伙实施.

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

这篇关于防止在ObservableCollection.CollectionChanged事件上添加新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:21