删除ObservableCollection中的一项 [英] Remove one Item in ObservableCollection

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

问题描述

我有一些方法,例如:

public void RemoveItem(ObservableCollection<SomeClass> collection, SomeClass instance)
{
    if(collection.Contains(instance))
    {
        collection.Remove(instance);
    }
}

首先,即使集合包含实例, if 句子仍然返回 false

First, even the collection contains the instance, the if sentence still return false.

第二,我删除if语句,只需使集合可以删除实例即可。执行后,集合仍然保留其原始项目,其中仍然包含实例。

Second, I delete the if sentence, just make the collection can remove the instance. And after the execution the collection still kept its original items, which still include instance.

这是参考问题,但是如何解决?我只想从ObservableCollection中删除一项并保留其Observable功能(使我感到困惑的是此处 )。

Is it the Reference problem, but how to fix it? I just want to remove one item from the ObservableCollection and keep its Observable functionality (which puzzled me here).

推荐答案

您的问题是您正试图从集合中删除对象不在那个集合中。它可能具有相同的属性值,但是它不是同一对象。如果您的对象具有唯一可识别的属性,例如, Id

Your problem is that you are trying to remove an object from the collection that is not in that collection. It might have the same property values, but it is not the same object. There is a simple way around this if your object has a uniquely identifiable property, such as Id:

public void RemoveItem(ObservableCollection<SomeClass> collection, SomeClass instance)
{
    collection.Remove(collection.Where(i => i.Id == instance.Id).Single());
}

想法是我们得到了 actual 集合中的项目,然后将其传递到删除方法。

The idea is that we are getting the actual item from the collection and then passing that into the Remove method.

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

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