将ObservableCollection复制到另一个ObservableCollection

Sam*_*lex 0 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);
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*tle 7

您需要item在添加之前克隆引用的对象AllMetalRate,否则两者都ObservableCollections将引用同一对象.实现ICloneable接口on 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
    }

}
Run Code Online (Sandbox Code Playgroud)

在添加到之前克隆AllMetalRate:

foreach (var item in MetalRateOnDate)
{
    var clone = (RateModel)item.Clone();
    AllMetalRate.Add(clone);
}
Run Code Online (Sandbox Code Playgroud)