Friday, June 27, 2008
Persisting WPF Objects as XAML or XPS
Here's another thing people ask me about frequently: How can any in-memory WPF object be persisted as XAML? Here's how:
string xaml = System.Windows.Markup.XamlWriter.Save(some object);
This gives you the XAML that can then be persisted in a file or wherever, and it can be loaded dynamically or you could even use it as a new file in a project that gets compiled in. (Note that the created XAML can be pretty nasty compared to XAML crafted by hand or an editor).
Note: The System.Windows.Markup namespace also features a XamlReader object, which can be used to dynamically load XAML during runtime.
A similar scenario calls for converting to XPS. (XPS is basically the WPF version of PDFs). XPS is also XAML, but it is a little different in that XPS is a print-like presentation of what something looks like. XPS may use graphical elements (shapes) to represent something on screen, which is somewhat different from he above example that preserves the XAML objects as they were. (Conversion to XAML always saves a button as a <Button>, while XPS does whatever it wants to create something that looks the same, but it isn't an interactive button).
XML documents can be really great if you want to preserve the look of something exactly as is. This is generally used to save FlowDocuments as XPS. Check out this blog post for some details on that.
Posted @ 2:45 PM by Egger, Markus (email@example.com)