I want to serialize wpf user control xaml and codebehind. XamlWriter.Save()
only serialize's xaml so what can I do in this situation? My situtation is I have a usercontrol which include custom methods, subscribed events (ex: button click) When I deserialize usercontrol (for create usercontrol at runtime) I want to run that events and methods. Sorry my english isn't very good.

- 3,741
- 12
- 49
- 72

- 49
- 2
- 9
-
2Why would you want to serialize the code? – gideon Aug 03 '11 at 05:28
-
Could you explain why you want to do this? Can't you use Reflector to get the C# code? – Emond Aug 03 '11 at 05:29
-
1because I will create usercontrol at runtime. For example; a button, which is in user control, has click event(subscribed) when deserialize usercontrol I want to run that event. – Sinan Oran Aug 03 '11 at 05:34
1 Answers
Just an idea, you can use MEF to built up a plugin structure for your user control. You want to create a user control on the fly but the event handler still should be hardcoded somewhere else in your project; with the plugin structure, you can just collect the plugin and reuse it; the events can be handled by a command something. Maybe giving a scenario and we can figure out more detail.
Plus, ISerializable provides a way for custom binary serialization for field, not for methods or events. Here is a related question: What is the point of the ISerializable interface? ; on the other hand, you can still try some pattern like how the web control save its view state; for example two virtual methods:
public virtual byte[] SaveState(); // it saves the states for your custom control
public virtual void LoadState(byte[] state) // it restore your state back to the control.
The custom code should be like:
byte[] state = controlA.SaveState(); // this method saves its own state.
YourControl controlB = new YourControl();
controlB.LoadState(state); // this method load the save state from A to B itself.
For the event, every event has a handler name, you can also serialize its handler name to the state and find it back by the saved name from its naming container alike. I don't have any experience to save the method.
If you still want to save and load state including fields, events and method, maybe serialization is not the proper way you are looking for I think.
-
UserControl inherit ISerializable interface. I serialize and deserialize usercontrol without losing any member ,event,method. Can I explain because my english is not very good – Sinan Oran Aug 04 '11 at 08:18
-
You are welcome, hope it helps. We used to find the serialization solution for a long time but none of them is 100% perfect. :) – Howard Aug 05 '11 at 06:36