如何在
没有第一次收藏的情况下将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)
造成这种情况的原因是什么?如何解决?
您需要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)
归档时间: |
|
查看次数: |
6656 次 |
最近记录: |