从CollectionChanged事件处理程序中的ObservableCollection中删除一项 [英] Remove an item from an ObservableCollection in a CollectionChanged event handler

查看:362
本文介绍了从CollectionChanged事件处理程序中的ObservableCollection中删除一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将某些项目添加到ObservableCollection之后将其拒绝.我无法继承ObservableCollection的子类或使用任何类型的视图,因此我似乎仅限于使用定义的一个事件处理程序(CollectionChanged)对禁止的项目执行.Remove().如果项目在引发事件和处理事件之间的短时间内存在,那就很好了;这些项目不应只保留在集合中.似乎不允许在CollectionChanged事件处理程序中调用.Remove().在运行时.NET抛出InvalidOperationException:

I'm hoping to be able to reject some items after they have been added to an ObservableCollection. I am not able to subclass the ObservableCollection or use any sort of view, so I seem to be limited to using the one event handler defined (CollectionChanged) to perform a .Remove() on the prohibited items. It's fine if the items exist for the short period between the event being raised and then handled; the items should just not persist in the collection. Calling .Remove() within the CollectionChanged event handler doesn't appear to be allowed. At runtime .NET throws an InvalidOperationException:

在CollectionChanged事件期间无法更改ObservableCollection."

"Cannot change ObservableCollection during a CollectionChanged event."

我个人认为.NET应该允许我这样做.如果创建无限循环,那是我自己的糟糕透顶.

Personally I think .NET should allow me to. If I create an infinite loop, it's my own darn fault.

我想使用的代码如下:

myCollection.CollectionChanged += (sender, args) =>
{
    if (args.Action == NotifyCollectionChangedAction.Remove)
        return;
    foreach (var itm in myCollection)
    {
        if (itm.name == "Fred")
            myCollection.Remove(itm);
    }
}

我不确定我有什么选择.使用调度程序似乎无效.触发另一个事件并将.Remove调用放置在另一个处理程序中是唯一想到的其他选择.

I'm not sure what options I have. Using a dispatcher doesn't seem to work. Triggering another event and placing the .Remove call in another handler is the only other option that comes to mind.

推荐答案

查看使用Observable的常见错误收藏.

话虽如此,如果您仍然想走这条路-您可以旋转

Having said that, if you still want to go this route - you can spin a new Thread

这篇关于从CollectionChanged事件处理程序中的ObservableCollection中删除一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆