简体   繁体   中英

How to serialize a control by XMLSerializer in C#

I'm developing an app which user can add some controls (Button, Label and...) dynamically to a panel and then save the form with all added controls. For saving I use XMLSerializer but it gives me this error

Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface.

I want to know how can I save controls in XML file? If it's not possible, is there any other way to do this?

Edit: ( Solved )

I found a good project which is exactly what I'm looking for:

Easy Form Design at Run Time C# Windows Forms

Thank you

Controls have dozens of properties. When you create a control, you set only some properties, and the rest remain by default. You need to save only the specified properties.

Create a class to store the desired properties:

public class ControlValueObject
{
    public string Type { get; set; }
    public string Text { get; set; }
    public int Top { get; set; }
    public int Left { get; set; }
    // Add the properties you need
}

Then create a collection of these objects and serialize it:

var label = new Label { Text = "Sample", Top = 10, Left = 20 };
var button = new Button { Text = "Click", Top = 40, Left = 20 };

panel.Controls.Add(label);
panel.Controls.Add(button);

var controls = panel.Controls.OfType<Control>()
    .Select(c => new ControlValueObject { Type = c.GetType().Name, Text = c.Text, Left = c.Left, Top = c.Top })
    .ToList();

var ser = new XmlSerializer(controls.GetType());
ser.Serialize(stream, controls);

How to make deserialization, I think, you will guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM