3

How to serialize the properties in user control?

I have tried the following code but I got InvalidOperationExceptio, While creating the XmlSerializer object

MyUserControl userControl = new MyUserControl();
XmlSerializer serializer = new XmlSerializer(typeof(MyUserControl));
Stream stream = new MemoryStream();
TextWriter writer = new StreamWriter(stream);
serializer.Serialize(writer, userControl);   

Exception:

System.InvalidOperationException was unhandled

HResult=-2146233079

Message=There was an error reflecting type 'Demo.MyUserControl'.

Ponraja
  • 570
  • 2
  • 6
  • 17
  • For a similar problem, I data bound my control to a class and then serialized that, are you talking about data binding attributes such as the user controls name or custom properties/values? – Sayse Apr 09 '13 at 09:25
  • Have you tried this? http://www.codeproject.com/Articles/27158/XamlWriter-and-Bindings-Serialization – Adolfo Perez Apr 09 '13 at 12:23

1 Answers1

1

You should not do it like this IMHO.

You should write a separate "Data Transfer Object (DTO)" style class to hold the data that you want to serialize, and use that instead. (You'd need to write Transform methods to convert the data back and forth of course.)

Otherwise you will couple your data storage format tightly to your user control.

If you use a separate class for serializing, it will make it much more manageable and flexible especially if you need to add new properties in the future.

If you really must serialize the user control (and I highly recommend that you don't) you could try using DataContract serialization which has an "opt-in" mechanism for which properties get serialized, rather than the "opt-out" mechanism for the older serialization.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • DataContract serialization doesn't solve the problem as UserControl is neither marked as Serializable or DataContract, so any derived type cannot be serialized with DataContractSerializer. – Payton Byrd Mar 27 '14 at 20:44