wpf 如何复制可观察集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4179606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy observable collection
提问by Relativity
I have
我有
Observablecollection<A> aRef = new Observablecollection<A>();
bRef = aRef();
In this case both point to same ObservableCollection
... How do I make a different copy?
在这种情况下,两者都指向相同的ObservableCollection
...如何制作不同的副本?
回答by Aliostad
Do this:
做这个:
// aRef being an Observablecollection
Observablecollection<Entity> bRef = new Observablecollection<Entity>(aRef);
This will create an observable collection but the items are still pointing to the original items. If you need the items to point a clone rather than the original items, you need to implement and then call a cloning method.
这将创建一个可观察的集合,但项目仍然指向原始项目。如果需要项目指向克隆而不是原始项目,则需要实现然后调用克隆方法。
UPDATE
更新
If you try to add to a list and then the observable collection have the original list, just create the Observablecollection by passing the original list:
如果您尝试添加到列表中,然后 observable 集合具有原始列表,只需通过传递原始列表来创建 Observablecollection:
List<Entity> originalEnityList = GetThatOriginalEnityListFromSomewhere();
Observablecollection<Entity> bRef = new Observablecollection<Entity>(originalEnityList);
回答by Jaime Marín
You could implement ICloneable
interface in you entity definition and then make a copy of the ObservableCollection
with a internal cast. As a result you will have a cloned List
without any reference to old items. Then you could create your new ObservableCollection
whit the cloned List
您可以ICloneable
在实体定义中实现接口,然后ObservableCollection
使用内部转换制作 的副本。因此,您将拥有一个List
没有任何参考旧项目的克隆。然后你可以创建你的新ObservableCollection
丝毫克隆 List
public class YourEntity : ICloneable {
public AnyType Property { get; set; }
....
public object Clone()
{
return MemberwiseClone();
}
}
The implementation would be
实施将是
var clonedList = originalObservableCollection.Select(objEntity => (YourEntity) objEntity.Clone()).ToList();
ObservableCollection<YourEntity> clonedCollection = new ObservableCollection<YourEntity>(clonedList);