简体   繁体   English

如何在 C# 中通过 XMLSerializer 序列化控件

[英]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为了保存我使用 XMLSerializer 但它给了我这个错误

Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface.不能序列化 System.ComponentModel.Component.Site 类型的 System.ComponentModel.ISite 成员,因为它是一个接口。

I want to know how can I save controls in XML file?我想知道如何将控件保存在 XML 文件中? 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 在运行时轻松设计窗体 C# Windows 窗体

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.如何进行反序列化,我想,你会猜到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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