首页 > 解决方案 > 通过调用不同类的方法在表单中创建标签动态布局

问题描述

正如标题实现的那样,我如何调用在表单中添加控件的方法,比如 Form1。我想调用该方法并在内部创建几个控件,例如调用它的表单中的文本框或标签

标签: c#

解决方案


您可以在静态类中准备控件并在两种表单中使用它,如下所示

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Controls.Add(MyControls.AddLabel());
    }
}

public static class MyControls
{
    public static Control AddLabel()
    {
        Label label = new Label
        {
            AutoSize = true,
            Location = new Point(48, 47),
            Name = "label1",
            Size = new Size(46, 17),
            TabIndex = 1,
            Text = "label1"
        };
        return label;
    }
}

推荐阅读