0

I'm working on a WPF project and have implemented a very simple way to undo one level of change which works nicely throughout the project except for one case where changes to an object's property reflects in the MemberwiseClone.

What I am doing is to do a MemberwiseClone in my object before adding or editing properties in that object, and then if the user wants to undo, I copy each property from the MemberwiseClone object back into my current object.

Because I am using WPF binding, using the MemberwiseClone is attractive to me because up until now, any change made in a property was not reflected in the MemberwiseClone. This time I have a property in my object that is an ObservableCollection of another object, and what is happening is that if I add an item to the ObservableCollection, it also gets added to the object created by MemberwiseClone and I can never truly undo.

Is there any way around this? Any thoughts you might have on this are welcomed.

Thanks.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Mike Malter
  • 1,018
  • 1
  • 14
  • 38

1 Answers1

1

According to Object.MemberwiseClone Remarks the object references in your ObservableCollection will be copied but not the referenced object itself. Therefore your undo collection references the same possible changed objects.

You need a deep copy, not a shallow one. Take a look at How do you do a deep copy an object in .Net (C# specifically)?

Community
  • 1
  • 1
LPL
  • 16,827
  • 6
  • 51
  • 95
  • I am working with the extension method in the link, however I get the following exception: Type 'System.ComponentModel.PropertyChangedEventManager' in Assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable. Any thoughts? I have marked all of my classes as Serializable. – Mike Malter May 04 '12 at 23:26
  • You have to use [Serializable] attribute on your class with ObservableCollection. See [Basic Serialization](http://msdn.microsoft.com/en-us/library/4abbf6k0%28v=vs.100%29.aspx) for an example. – LPL May 04 '12 at 23:34
  • LPL, Yes, I had marked all of my classes as Serializable, but needed the NonSerializedAttribute to make this work. Thank you very much for the link and your very helpful answer. – Mike Malter May 05 '12 at 00:28