Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Serialize DependencyObject: It's easy !

5.00/5 (1 vote)
25 Feb 2010Ms-PL 1  
An easy way to perform serialization of these objects

You often read on the web that the DependencyObjects are not marked as serializable and that this is a major drawback...

But there is an easy way to perform serialization of these objects: use XAMLWriter and XAMLReader:

C#
public class MyDependencyObject : DependencyObject
{
public static readonly DependencyProperty MyDependencyPropertyProperty =
  DependencyProperty.Register("MyDependencyProperty", 
	typeof(String), typeof(MyDependencyObject));
 
  public String MyDependencyProperty
  {
    get { return (String)GetValue(MyDependencyObject.MyDependencyPropertyProperty); }
    set { SetValue(MyDependencyObject.MyDependencyPropertyProperty, value); }
  }
 
}
 
...
 
MyDependencyObject obj = new MyDependencyObject();
obj.MyDependencyProperty = "One love";
String serializedString = XamlWriter.Save(obj);
Console.WriteLine(serializedString);

It will produce something like this:

XML
<MyDependencyObject MyDependencyProperty="One love" 
	xmlns="clr-namespace:ANTOINE.Jonathan;assembly=ANTOINE.Jonathan" />
Shout it kick it on DotNetKicks.com

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)