c# - 如何通过在 C# 中单击按钮将用户控件加载到面板

标签 c# winforms user-controls panel

我想用按钮将用户控件加载到面板,但是当我尝试这段代码时它什么也没显示。我想知道是否有解决我的问题的方法,因为我已经尝试了很多来自互联网的解决方案,但没有任何效果。

这是我的代码:

关于用户控制

public partial class UserControl1 : UserControl
{
    public static UserControl1 _instance;
    public static UserControl1 Instance {
        get {
            if (_instance == null)
                _instance = new UserControl1();
            return _instance;
        }
    }
    public UserControl1()
    {
        InitializeComponent();
    }
}

在 winform 上点击按钮

private void b1_Click(object sender, EventArgs e)
    {
        if (!panel5.Controls.Contains(UserControl1.Instance))
        {
            panel5.Controls.Add(UserControl1.Instance);
            UserControl1.Instance.Dock = DockStyle.Fill;
            UserControl1.Instance.BringToFront();
        }
        else
            UserControl1.Instance.BringToFront();
    }

主窗体

enter image description here

用户控制

enter image description here

感谢您的关心。

最佳答案

试试这个。 希望这对您有所帮助

private void set2ControlTopanel(control f) {

    try {
        p2Form = f;
        p2Form.Dock = DockStyle.Fill;
        p2Form.Show();
        panelTop.Controls.Add(p2Form);
        p2Form.BringToFront();
    }
    catch (Exception ex) {
        MsgBox(ex.Message);
    }

}

关于c# - 如何通过在 C# 中单击按钮将用户控件加载到面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501823/

相关文章:

c# - 在嵌入的 C# 代码中获取 JavaScript 变量

c# - 为什么我的应用程序在 Release模式下崩溃但在 Debug模式下不崩溃?

c# - Renci ssh.net - 连接时从表单创建控制台屏幕

c# - 将 app.config 配置部分重新定位到 AppData 文件夹

c# - 如何以编程方式将 ASCX 内的 ASP.NET 控件添加到外部 RequiredFieldValidator?

c# - 自定义控件 BorderThickness

c# - 如何从 RSS 提要项中获取所有可能的图像 URL?

c# - 通过android查看在本地机器上运行的网站

c# - 如何将 win form 保存为 image/pdf?

WPF:带有 2 个(或更多!)ContentPresenters 的模板或 UserControl 以在 'slots' 中呈现内容