How do I make a Deep Copy of a UIElement?

2019-06-25 11:13发布

问题:

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?

回答1:

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.



回答2:

If you've already gone through the trouble of manually saving the previous values, it seems like you are pretty close to simply creating a new instance of the object and setting its properties.

If the UI element has been marked serializable, you can clone the object pretty easily.