One of the most useful features of WPF is the ability to save and load objects with XamlWriter and XamlReader. There are some limitations to their use, for example, there may be differences in the design time and run time representations of an object – the runtime representation will always be the one that gets saved. Serialization Limitations of XamlWriter.Save does a pretty decent job explaining the limitations, as well as the scenarios for realistic use of this functionality.
Where XamlReader and XamlWriter shine is when you need to save and load vector graphics. Most, if not all graphical objects in Windows Presentation Foundation can be persisted in this way. One area where I ran into a little difficulty was when I attempted to serialize StreamGeometry objects. For the uninitiated, StreamGeometry is the high performance/low overhead alternative to using PathGeometry. StreamGeometries represent their data internally as a stream of bytes, which is serialized in path ‘mini-language’.
Now this is great, since use of mini-language helps keep the size of the resulting markup down, but as I found out, it is important to note that not *all* StreamGeometry states can be represented in this way. For example, setting stroked=false for any segment of your StreamGeometry will prevent it’s data from being serialized. It looks like calls to BeginFigure() also require that filled=true be set as well. This can be confusing, since XamlWriter doesn’t throw an exception – it simply serializes the StreamGeometry with no content.
Another issue has to do with loading serialized StreamGeometries – in the current CTP (and dev) bits, StreamGeometries cannot be loaded, due to some interactions between certain freezables and the Xaml Parser. In my situation, wrapping up my StreamGeometries into GeometryDrawings works, and I can even retrieve the StreamGeometry from the GeometryDrawing upon load. Since I also need to save the Pen used to stroke the StreamGeometry, this makes sense in my scenario. Anthony Hodson from Microsoft also suggested wrapping StreamGeometries in an Arraylist – for more detail, see this thread in the MSDN Avalon forums.
One other issue I have experienced is performance related. Simply put, XamlReader.Load seems to be a whole lot faster than XamlWriter.Save for the same object. I’m not surprised, since I’m sure the Xaml Parser has recieved a whole lot more attention than the serialization mechanism behind XamlWriter.Save. Once I’ve done some more testing with my scenario, I’m hoping to get a developer to comment on this.