Serialize DependencyObjects

One often reads that the ones DependencyObjects are not marked how being serializable (in the sense that the DependencyObject class is not decorated by the attribute Serializable) and that may be a problem. Indeed when one implements the interface IEditableObject, it is very easy to serialize the object and deserialize it when canceling the edition. But how do we deal with DependencyObject?`

Do not worry the solution is very simple: we use XAMLWriter and XAMLReader.

MyDependencyObject obj = new MyDependencyObject();
obj.WebSite = "http://www.meziantou.net";
string serializedString = XamlWriter.Save(obj);

serializedString contains :

<MyDependencyObject
    Website="http://www.meziantou.com"
    xmlns="clr-namespace:Meziantou;assembly=Meziantou" />
Follow me:
Enjoy this blog? Buy Me A Coffee Donate with PayPal

Leave a reply