将ObservableCollection复制到另一个ObservableCollection [英] Copy ObservableCollection to another ObservableCollection

查看:1214
本文介绍了将ObservableCollection复制到另一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆