XamlServices class in .Net 4.0

XAML has up to now played a big role in WPF and Silverlight and is seen as a markup language to design GUIs. That is not quite true. XAML describes objects, their properties and their relations. It is not limited to designing user interfaces. That is why XAML has been separated from WPF and Silverlight in .NET framework 4.0.

Let's assume you have a class BigSerializableObject and want to save it to a file with all properties and attached objects. Later, you want to be able to load it again from the file and get a new instance which is a perfect copy of the object you originally serialized. You might do this with XML. Serializing is not much of a problem. Deserializing is a completely different story. You would have to navigate through the XML nodes, create instances of the required objects, fill them with the proper values and assemble them according to the structure of the XML. That also means writing lots of code.

Things get far easier when using the System.Xaml.XamlServices class. Serializing the object is very similar to what you might be used to from XML:

That's it. Your object has just been serialized to XAML into the file Test.xaml. The only condition is that your object and all objects attached to it must be serializable.

Now we want to load our object again from the file Test.xaml. If possible, we want it as an object instance, just like it was before. And we don't want to write any code which constructs the object from the file. Try this:

That depends on what you need them for. I found this in the MSDN, just as somebody already pointed out above:

Important

XamlServices is not the recommended XAML reading or XAML writing API set if you are processing WPF-defined types, or types based on WPF. For WPF usage, use System.Windows.Markup.XamlReader for reading or loading XAML (or BAML); and System.Windows.Markup.XamlWriter for writing back XAML. These classes use .NET Framework XAML Services APIs and the XAML readers and XAML writers internally in their implementation; however, they also provide support and specialized XAML schema context for WPF-specific concepts, such as optimizations for dependency properties and WPF known types.

Unfortunately, the MSDN did not mention this class to be available for Silverlight, so it appears like serializing objects with this class is not supported right now.

"I just exchanged opinions with my boss. I went in with mine and came out with his." - me, 2011---I am endeavoring, Madam, to construct a mnemonic memory circuit using stone knives and bearskins - Mr. Spock 1935 and me 2011