将ObservableCollection复制到另一个ObservableCollection [英] Copy ObservableCollection to another ObservableCollection
问题描述
如何将ObservableCollection
项目复制到另一个ObservableCollection
没有引用第一个收藏夹?此处ObservableCollection
项值的更改会影响两个集合.
How to copy ObservableCollection
item to another ObservableCollection
without reference of first collection? Here ObservableCollection
item value changes affecting both collections.
代码
private ObservableCollection<RateModel> _AllMetalRate = new ObservableCollection<RateModel>();
private ObservableCollection<RateModel> _MetalRateOnDate = new ObservableCollection<RateModel>();
public ObservableCollection<RateModel> AllMetalRate
{
get { return this._AllMetalRate; }
set
{
this._AllMetalRate = value;
NotifyPropertyChanged("MetalRate");
}
}
public ObservableCollection<RateModel> MetalRateOnDate
{
get { return this._MetalRateOnDate; }
set
{
this._MetalRateOnDate = value;
NotifyPropertyChanged("MetalRateOnDate");
}
}
foreach (var item in MetalRateOnDate)
AllMetalRate.Add(item);
是什么原因造成的,我该如何解决?
What is causing this and how can I solve it?
推荐答案
您需要先克隆item
引用的对象,然后再将其添加到AllMetalRate
中,否则两个ObservableCollections
都将引用同一对象.在RateModel
上实现ICloneable
接口以返回一个新对象,并在调用Add
之前调用Clone
:
You need to clone the object referenced by item
before it's added to AllMetalRate
, otherwise both ObservableCollections
will have a reference to the same object. Implement the ICloneable
interface on RateModel
to return a new object, and call Clone
before you call Add
:
public class RateModel : ICloneable
{
...
public object Clone()
{
// Create a new RateModel object here, copying across all the fields from this
// instance. You must deep-copy (i.e. also clone) any arrays or other complex
// objects that RateModel contains
}
}
在添加到AllMetalRate
之前先进行克隆:
Clone before adding to AllMetalRate
:
foreach (var item in MetalRateOnDate)
{
var clone = (RateModel)item.Clone();
AllMetalRate.Add(clone);
}
这篇关于将ObservableCollection复制到另一个ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!