1
votes

According to this article deep copying, I'm trying to make a deep copy of my userControl. So in my main viewModel I have:

public object Clone()
    {
        var cloneControl = (ISelectableViewModel) SelectedObject; //SelectedObject it's current userControl
        return cloneControl.Clone();

    }

My usercontrol have also simple usercontrol inside. So code for userControl Clone method is:

 public override object Clone()
    {
        var partikel1Clone = (UserControl05Partikel1ViewModel) MemberwiseClone();
        partikel1Clone.UserControl1.ViewModel = (ISelectableViewModel) UserControl1.ViewModel.Clone();
        return partikel1Clone;
    }

And my simple userControl's Clone method is:

 public override object Clone()
 {
     return MemberwiseClone();
 }

The problem is that my cloned object changes, when I change main object. Any ideas where am I wrong?

1
Memberwise Clone is only one level deep.Henk Holterman
@Henk yes, but I am calling Clone method for my inside control which calls another MemberwiseSasha
I would consider Controls (UIElements) as not clonable... You don't own the source and there's 15 layers of inheritance in play here.Henk Holterman
You would be better to come up with a separate description of the "copyable" bits of the control, e.g add a method to list them out into xml, json, even name value, and then add a constructor that took the description as an argument. What you are doing is complex and way too fragile as you don't own most of the code.Tony Hopkinson
@TonyHopkinson thnx for advice. I'll give a trySasha

1 Answers

-1
votes

Binary serialisation is probably the simplest way to do a true deep clone.

using(var stream = new MemoryStream())
{

    var formatter = new BinaryFormatter();
    formatter.serialize(stream, objectToClone);
    stream.Seek(0, SeekOrigin.Begin);
    return (MyType)formatter.Deserialize(stream);    
}