Persisting Objects

XamlWriter and XamlReader aren't limited to working with user interface elements. You can persist any object using these tools, in effect creating a form of XAML-based object serialization. For example, suppose you have the non-user interface class Dog shown in Listing 6-16.

Listing 6-16. Dog Class public class Dog {

public string Name { get; set; } public string Breed { get; set; }

public string Bark() {

return "Woof, woof!";

If you instantiate this object, you can serialize it using XamlWriter and XamlReader, as shown in Listing 6-17.

Listing 6-17. Instantiating a Dog Object

Dog oDog = new Dog(); oDog.Breed = "Pit Bull"; oDog.Name = "Elke";

string szXAML = XamlWriter.Save(oDog);


The variable szXAML holds the following string, which indicates the class's property settings and its host assembly:

<Dog Name=\"Elke\" Breed=\"Pit Bull\" xmlns=\"clr-namespace:DataDrivenWPF;assembly=DataDrivenWPF\" />

You can then reverse this process by extracting the XAML definition and casting it to an object of type Dog like this:

Dog oMyDog = ((Dog)XamlReader.Parse(szXAML));

0 0

Post a comment