将 ObservableCollection 复制到另一个 ObservableCollection
Copy ObservableCollection to another ObservableCollection
如何将 ObservableCollection
项目复制到另一个 ObservableCollection
没有参考第一个系列?这里 ObservableCollection
项目值更改影响两个集合。
代码
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);
是什么原因造成的,我该如何解决?
您需要先克隆 item
引用的对象,然后再将其添加到 AllMetalRate
,否则两个 ObservableCollections
将引用同一个对象。将 RateModel
上的 ICloneable
接口实现到 return 一个新对象,并在调用 Add
:
之前调用 Clone
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
之前克隆:
foreach (var item in MetalRateOnDate)
{
var clone = (RateModel)item.Clone();
AllMetalRate.Add(clone);
}
如何将 ObservableCollection
项目复制到另一个 ObservableCollection
没有参考第一个系列?这里 ObservableCollection
项目值更改影响两个集合。
代码
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);
是什么原因造成的,我该如何解决?
您需要先克隆 item
引用的对象,然后再将其添加到 AllMetalRate
,否则两个 ObservableCollections
将引用同一个对象。将 RateModel
上的 ICloneable
接口实现到 return 一个新对象,并在调用 Add
:
Clone
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
之前克隆:
foreach (var item in MetalRateOnDate)
{
var clone = (RateModel)item.Clone();
AllMetalRate.Add(clone);
}