繁体   English   中英

C#如何使用列表类作为自定义窗体的属性

[英]C# How to use List Class as Property of Custom Form

我正在尝试为自定义表单创建一个由List<>组成的属性。 请在下面查看我的代码:

//Property of Custom Form
public ParametersList Parameters { get; set; }

public class ParametersList : List<Parameter>
{
    private List<Parameter> parameters = new List<Parameter>();
    public void AddParameter(Parameter param)
    {
        parameters.Add(param);
    }
}

public class Parameter
{
    public String Caption { get; set; }
    public String Name { get; set; }
}

现在,“属性参数”出现在自定义窗体上,但是问题是当我单击“参数”属性的省略号并添加一些列表时,按“确定”按钮时,该列表没有保存。 因此,每当我按省略号时,该列表就很清楚。

这是我要实现的示例:
图片

Igor的注释指出了问题所在,仅使用List<Parameter>而不使用自定义类。 这就是为什么我认为这就是问题所在:

您的形式将项目添加到ParametersList ,而不是私人List<Parameter>内部 ParametersList

因此,您的类一个参数列表(通过继承),并且具有一个参数列表(通过封装)。 似乎您所需要的只是存储参数的集合,因此我完全不需要自定义类。

您需要自定义控件中的Parameter对象列表。 只需在控件上提供List<Parameter>属性即可完成此操作。 这是使用用户表单的示例:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        ParameterList = new List<Parameter>();
    }

    [Category("Custom")]
    [Description("A list of custom parameters.")]
    public List<Parameter> ParameterList { get; }
}

1号

您的主要问题是,在设计表单时添加到列表中的项目在运行应用程序时不会保留。 这是可以预期的,因为设计人员不会将控件的完整设计状态保存在表单中。 它主要保存位置,名称和样式,但不保存内容。

在从文件,数据库或以编程方式加载表单时,您将需要填写列表。 这应该在OnLoad()方法中完成:

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        ParameterList.Add(new Parameter() { Name="First", Caption="The first parameter" });
    }

对于这样的事情,我更喜欢序列化到XML文件中,该XML文件在加载表单时自动加载,并在表单关闭时自动保存。 但这是另一个问题的讨论主题。

您可以通过创建要使用的自定义列表类代替List<Parameter>来改善视觉效果。

[TypeConverter(typeof(ExpandableObjectConverter))]
public class CustomParameterList : System.Collections.ObjectModel.Collection<Parameter>
{
    public override string ToString() => $"List With {Count} Items.";
    public void Add(string name, string caption) => Add(new Parameter() { Name = name, Caption = caption });
}

然后你控制课

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        ParameterList = new CustomParameterList();
    }

    [Category("Custom")]
    [Description("A list of custom parameters.")]
    public CustomParameterList ParameterList { get; }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        ParameterList.Add("First", "The first parameter");
    }

}

这将创建以下内容:

2号

3号

暂无
暂无

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

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