views:

180

answers:

1

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?

+1  A: 

Here is one technique.

First create a MarkupExtension that can construct the desired class. A super-simple one would be:

public class DocumentPageExtension : MarkupExtension
{
  public Visual Visual { get; set; }
  public Size PageSize { get; set; }
  public Rect BleedBox { get; set; }
  public Rect ContentBox { get; set; }

  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    return new DocumentPage(Visual, PageSize, BleedBox, ContentBox);
  }
}

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.

Ray Burns
I have a vague memory trying something like that. I think it then became the Visual instance inside the DocumentPage that was equally problematic. And indeed some problems with the read only properties. But Ill check the MarkupExtension, thanks!
mizipzor