如何将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);
造成这种情况的原因是什么?如何解决?
答案 0 :(得分:7)
您需要克隆item
引用的对象,然后才将其添加到AllMetalRate
,否则ObservableCollections
都将引用同一个对象。在ICloneable
上实施RateModel
界面以返回新对象,并在致电Clone
之前致电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
之前克隆:
foreach (var item in MetalRateOnDate)
{
var clone = (RateModel)item.Clone();
AllMetalRate.Add(clone);
}