winforms 无法在文件代码中声明UserControl

xa9qqrwz  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(109)

我遇到了一个问题。我创建了一个UserControl并保存它,它出现在工具箱中。我可以正常地将它从工具箱中删除。但是,我无法在文件代码中将它声明为变量。请帮助我,好吗?这是UserControl的文件代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Music_Player_Project_IT008N13.Controls;

namespace Music_Player_Project_IT008N13.Music_design_User_Control
{
    public partial class LocationPanel : UserControl
    {
        public LocationPanel()
        {
            InitializeComponent();
        }
        public delegate void DoEvent(string maSo, string tenSV, string khoa, string diemTB);
        public event DoEvent RefeshDgv;
        private void btnDelete_Click(object sender, EventArgs e)
        {
            
        }
    }
}
disbfnqx

disbfnqx1#

当您"正常地将其从工具箱中拖出"时,设计器将为新用户控件生成成员声明,并 * 还 * 将其添加到forms Control集合中。据我所知,您的问题表明您希望在代码中声明您的用户控件变量。如果这是目标,我们必须执行与设计器相同的操作,并将其添加到要将其放入的容器的Controls集合中。

    • 示例**
  • 使用代码添加FlowLayoutPanel,然后也在代码中向其添加3个CustomUserControls。*

public partial class MainForm : Form
{
    public MainForm() => InitializeComponent();
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // Declare a flow layout panel in code.
        // Add it to the main form control collection
        var flowLayoutPanel = new FlowLayoutPanel
        {
            Name = "flowLayoutPanel",
            Dock = DockStyle.Fill,
        };
        this.Controls.Add(flowLayoutPanel);

        for (char c = 'A'; c < 'D'; c++)
        {
            var userControl = new CustomUserControl
            {
                Name = $"userControl{c}",  // No space, start with lowercase
                Text = $"UserControl {c}", // Visible name
                Margin = new Padding(10, 2, 10, 2),
                Width = flowLayoutPanel.Width - 20,
            };
            flowLayoutPanel.Controls.Add(userControl);
        }

        // T E S T
        CustomUserControl? loopback = GetUserControl("userControlA");
        Debug.Assert(loopback != null, "Expecting to retrieve user control by name");
    }

然后,若要使用该控件,请按名称从Controls集合中检索它。

CustomUserControl? GetUserControl(string name)
    {
        var layoutPanel = Controls["flowLayoutPanel"] as FlowLayoutPanel;
        return layoutPanel.Controls[name] as CustomUserControl;
    }
}

其中:

public partial class CustomUserControl : UserControl
{
    public CustomUserControl() => InitializeComponent();
    public new string Text
    {
        get => label1.Text; 
        set => label1.Text = value;
    }
}

相关问题