How can we make a deep copy of a WPF object?

We can make a deep copy of  a WPF object using XamlWriter and XamlReader. Here the XamlWriter.Save is used to serialize the contents of a WPF object into xaml string.  XamlReader.Load is used to parse XAML string into a WPF object. To make deep copy of an wpf UIelement , you can use the following method.

   1: public UIElement DeepCopy(UIElement element)
   2:    {
   3:        string shapestring = XamlWriter.Save(element);
   4:        StringReader stringReader = new StringReader(shapestring);
   5:        XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
   6:        UIElement DeepCopyobject = (UIElement)XamlReader.Load(xmlTextReader);
   7:        return DeepCopyobject;
   8:    }

If you would like to make deep copy of  WPF  objects without XamlWriter, you have to use reflection .For that you have to navigate recursively inside the type to get all Dependency Properties and Dependency Objects as well as plain .net properties.

2 Comments

Comments have been disabled for this content.