避免在第二个集合中使用NotifyPropertyChanged

本文关键字:NotifyPropertyChanged 集合 第二个 | 更新日期: 2023-09-27 18:27:54

我有一个类BaseClassObservableCollection1<BaseClass>)的可观察集合,它实现了INotifyPropertyChanged和属性Raise the event when something changes。我想将调用数据库时得到的默认值存储在另一个可观察集合(ObservableCollection2<BaseClass>)中。我的视图绑定到ObervableCollection1,而不是2,但如果BaseClass发生变化,则由于BaseClass上的INotifyPropertyChanged,1和2中的值都会更新。我如何避免第二个ObservableCollection2<BaseClass>被新值更新?

避免在第二个集合中使用NotifyPropertyChanged

深度复制是关键,您所要做的就是让BaseClass实现ICloneable接口,然后添加复制对象所需的所有逻辑。可以使用二进制序列化对对象进行深度复制。

因此,首先,您的类必须标记为[Serializable],这样才能工作。

[Serializable]
    public class BaseClass: ICloneable
    {
        /*
        Base Class Mumbers ...
        */
        public object Clone()
        {
            var bf = new BinaryFormatter();
            using (Stream str = new MemoryStream())
            {
                bf.Serialize(str, this);
                str.Seek(0, SeekOrigin.Begin);
                return bf.Deserialize(str);
            }
        }
    }

并最终复制您的源集合

var copiedCollection = new ObservableCollection<BaseClass>(sourceCollection.Select(a => (BaseClass)a.Clone()));
相关文章:
  • 没有找到相关文章