4

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
GWLlosa
  • 23,995
  • 17
  • 79
  • 116

1 Answers1

3

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.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Rune Andersen
  • 1,650
  • 12
  • 15
  • Also if you don't show the object you recreate and just send it printing with different margins you probably need to call Measure(..) and Arrange(..) to get anything drawn. – Rune Andersen Jun 06 '11 at 20:25
  • Are those the only 2 things that need to be called? – GWLlosa Jun 07 '11 at 02:53
  • string XamlWriter.Save(Object) gives you a string and Object XamlReader.Parse(string xamlText) gives an object you can insert - so yes that should be it - you can probably do: var uielementcopy=(UIElement)XamlReader.Parse(XamlWriter.Save(myUIelement)); – Rune Andersen Jun 07 '11 at 07:34
  • It looks like you have to use XamlReader.Load(string) for silverlight - and the writer doesn't seem to be there .. take a look at this for a writer: http://www.davidpoll.com/2010/07/25/to-xaml-with-love-an-experiment-with-xaml-serialization-in-silverlight/ – Rune Andersen Jun 07 '11 at 11:03