Search code examples
printingsilverlight-4.0deep-copyuielement

How do I make a Deep Copy of a UIElement?


So I have a printing component that serves a Silverlight application. Other modules in this program have the ability to signal the printing component and pass it a UIElement, which the printing component will then draw to the screen. All well and good. The problem arises when I try to manipulate the UI Element in order to better format it to fit the user's selected paper size or anything to that effect; it seems that the UI element that is passed in is frequently the exact same instance of the one on the screen, and the screen element changes itself to match the 'print-only' changes I have made. For now, I can manually save the previous values, make my changes, and restore the previous values, but it would be easier/more robust/more efficient/more flexible if I had a way to, given the UI element, make a copy of the element, and manipulate that freely, without worrying about alterations or state on the original UI element. How can I programatically copy an instance of a UI element such that I have another instance with the same visual appearance?


Solution

  • I know 2 ways you can try:

    Save the object to a xaml string and recreate it from it. (XamlWriter.Save and XamlReader.Parse)

    Save the object with the serializer to a memorystream and recreate it from that - it is possible that not all objects are marked serializable so the other option might be the one to use.

    It might seem a bit much - but there are not so many ways to create a deep copy - and not any standard c# method that I know of.