将ObservableCollection复制到另一个ObservableCollection

时间:2015-03-12 19:08:35

标签: c# mvvm

如何将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);

造成这种情况的原因是什么?如何解决?

1 个答案:

答案 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);
}