65.9K
CodeProject is changing. Read more.
Home

Serialize DependencyObject : it's easy !

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (2 votes)

Feb 25, 2010

CPOL
viewsIcon

16434

You often read on the web that the DependencyObjects are not marked as serializable and that this is a major drawback of them...But there is a easy way to perform a serialization of these object : use XAMLWriter and XAMLReader :public class MyDependencyObject : DependencyObject{public...

You often read on the web that the DependencyObjects are not marked as serializable and that this is a major drawback of them... But there is a easy way to perform a serialization of these object : use XAMLWriter and XAMLReader :
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 : <MyDependencyObject MyDependencyProperty="One love" xmlns="clr-namespace:ANTOINE.Jonathan;assembly=ANTOINE.Jonathan" /> :)
Serialize DependencyObject : it's easy ! - CodeProject