Serialize DependencyObjects

 
 
  • Gérald Barré

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.

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

serializedString contains :

XAML
<MyDependencyObject
    Website="https://www.meziantou.com"
    xmlns="clr-namespace:Meziantou;assembly=Meziantou" />

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub