Ive found out that you can serialize a wpf component, in my example a FixedDocument
, using the XamlWriter
and a MemoryStream
:
FixedDocument doc = GetDocument();
MemoryStream stream = new MemoryStream();
XamlWriter.Save(doc, stream);
And then to get it back:
stream.Seek(0, SeekOrigin.Begin);
FixedDocument result = (FixedDocument)XamlReader.Load(stream);
return result;
However, now I need to be able to serialize a DocumentPage
as well. Which lacks a default constructor which makes the XamlReader.Load
call throw an exception.
Is there a way to serialize a wpf component without a default constructor?
Here is one technique.
First create a MarkupExtension that can construct the desired class. A super-simple one would be:
Now after XamlWriter writes your document, just replace "DocumentPage" with "my:DocumentPageExtension", adding an appropriate namespace declaration at the top of the file.
The resulting file should be readable by
XamlReader.Load
.It is possible that XamlWriter doesn't store the values of read-only properties such as those found in DocumentPage. (I almost always use a XamlWriter replacement I wrote a while back.) If it doesn't serialize these properties at all, the technique given here will need to be supplemented with some other way of getting those property values into the XAML in the first place.
Also note that a general constructor-calling MarkupExtension can be created rather than "special casing" every object that needs handling in this manner.