7

我在互联网上搜索了这个,但我找不到如何使用 C#

我想要做的是,当我点击我的NewTab按钮时,会出现一个新标签,其中包含与第一个标签上相同的控件。我看到了一些关于如何向UserControl表单添加 a 的信息,但 C# 没有类似的东西。

对于每个会说“发布你的代码”的人,我没有,所以不要费心这么说,我唯一的代码是程序的代码,这对任何人都没有帮助。

4

3 回答 3

9

编辑

我已经重写了我的解决方案以使用反射。

using System.Reflection;

// your TabControl will be defined in your designer
TabControl tc;
// as will your original TabPage
TabPage tpOld = tc.SelectedTab;

TabPage tpNew = new TabPage();
foreach(Control c in tpOld.Controls)
{
    Control cNew = (Control) Activator.CreateInstance(c.GetType());

    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(c);

    foreach (PropertyDescriptor entry in pdc)
    {
        object val = entry.GetValue(c);
        entry.SetValue(cNew, val);
    }

    // add control to new TabPage
    tpNew.Controls.Add(cNew);
}

tc.TabPages.Add(tpNew);

一些信息可以在这里找到。 http://www.codeproject.com/Articles/12976/How-to-Clone-Serialize-Copy-Paste-a-Windows-Forms

于 2013-01-24T17:35:19.190 回答
1

你最好的选择是看这篇文章:

代码项目

然后应用以下代码添加克隆的控件(这将在您的按钮单击处理程序代码中(基于文章):

    private void button1_Click(object sender, EventArgs e)
    {
        // create new tab
        TabPage tp = new TabPage();

        // iterate through each control and clone it
        foreach (Control c in this.tabControl1.TabPages[0].Controls)
        {
            // clone control (this references the code project download ControlFactory.cs)
            Control ctrl = CtrlCloneTst.ControlFactory.CloneCtrl(c);
            // now add it to the new tab
            tp.Controls.Add(ctrl);
            // set bounds to size and position
            ctrl.SetBounds(c.Bounds.X, c.Bounds.Y, c.Bounds.Width, c.Bounds.Height);
        }

        // now add tab page
        this.tabControl1.TabPages.Add(tp);
    }

然后你需要连接事件处理程序。将不得不考虑这一点。

于 2013-01-24T17:53:48.043 回答
1

我知道这是一个旧线程,但我只是为自己找到了一种方法,并认为我应该分享它。它非常简单,并且在 .Net 4.6 中进行了测试。

请注意,此解决方案实际上并没有创建新控件,只是将它们全部重新分配给新的 TabPage,因此每次更改选项卡时都必须使用 AddRange。新选项卡将显示完全相同的控件、内容和包含的值。

// Create an array and copy controls from first tab to it.
Array tabLayout = new Control [numberOfControls];
YourTabControl.TabPages[0].Controls.CopyTo(tabLayout, 0);

// AddRange each time you change a tab.
YourTabControl.TabPages[newTabIndex].Controls.AddRange((Control[])tabLayout);
于 2017-03-20T10:14:19.867 回答