Моя цель — клонировать эту TabPage< /code> со всеми элементами управления и соответствующими обработчиками событий (например, comboBox_SelectedIndexChanged, textBox_TextChanged, button_Click и т. д.) в новую TabPage.
Для этой цели я создал класс TabPageCloner следующим образом:
Код: Выделить всё
using System;
using System.Windows.Forms;
using System.Reflection;
public class TabPageCloner
{
public static TabPage CloneTabPage(TabPage originalTab)
{
// Create a new TabPage instance
TabPage newTab = new TabPage(originalTab.Text);
// Clone each control on the original tab
foreach (Control control in originalTab.Controls)
{
Control clonedControl = CloneControl(control);
newTab.Controls.Add(clonedControl);
}
return newTab;
}
private static Control CloneControl(Control originalControl)
{
// Create an instance of the original control's type
Control newControl = (Control)Activator.CreateInstance(originalControl.GetType());
// Copy basic properties
newControl.Text = originalControl.Text;
newControl.Size = originalControl.Size;
newControl.Location = originalControl.Location;
newControl.Anchor = originalControl.Anchor;
newControl.Dock = originalControl.Dock;
// Clone any nested controls (for containers like Panels, GroupBoxes, etc.)
if (originalControl.HasChildren)
{
foreach (Control childControl in originalControl.Controls)
{
Control clonedChild = CloneControl(childControl);
newControl.Controls.Add(clonedChild);
}
}
// Clone event handlers
CloneEvents(originalControl, newControl);
return newControl;
}
private static void CloneEvents(Control originalControl, Control newControl)
{
// Use reflection to clone event handlers
EventInfo clickEvent = originalControl.GetType().GetEvent("Click");
if (clickEvent != null)
{
FieldInfo eventField = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
object eventDelegate = eventField?.GetValue(originalControl);
if (eventDelegate is EventHandler eventHandlers)
{
foreach (Delegate handler in eventHandlers.GetInvocationList())
{
clickEvent.AddEventHandler(newControl, handler);
}
}
}
}
}
Код: Выделить всё
TabPage clonedTabPage = TabPageCloner.CloneTabPage(MyOriginalTabPage);
tabControl1.TabPages.Add(clonedTabPage);
tabControl1.SelectedTab = clonedTabPage;
А также элементы ComboBox вообще не клонируются.
Что я пропал?
Подробнее здесь: https://stackoverflow.com/questions/790 ... -a-tabpage