所以,我已将Panel
代码添加到我的flowLayoutPanel
:
Panel pnl = new Panel {Name = panelname}; //panelname is a name combined with a continous number
CopyControl(panel1,pnl, number);
pnl.Visible = true;
flowLayoutPanel1.Controls.Add(pnl);
(Panel
中我已经有一个flowLayoutPanel
,我只是复制了它的属性' s)
复制控制:
private void CopyControl(Control sourceControl, Control targetControl, int number)
{
// make sure these are the same
if (sourceControl.GetType() != targetControl.GetType())
{
throw new Exception("Incorrect control types");
}
foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
{
object newValue = sourceProperty.GetValue(sourceControl, null);
MethodInfo mi = sourceProperty.GetSetMethod(true);
if (mi != null)
{
sourceProperty.SetValue(targetControl, newValue, null);
}
}
try
{
foreach (Control c in sourceControl.Controls)
{
if (c.GetType() == typeof(Button))
{
Button btn = new Button();
btn.Name = "button" + number;
btn.Click += CopyTextToClipboard;
//get same location
Button btnold = this.Controls.Find("button1", true).FirstOrDefault() as Button;
btn.Text = btnold.Text;
btn.Location = btnold.Location;
btn.Size = btnold.Size;
targetControl.Controls.Add(btn);
}
else if (c.GetType() == typeof(RichTextBox))
{
RichTextBox rtb = new RichTextBox();
rtb.Name = "richTextBox" + number;
RichTextBox rtbold = this.Controls.Find("richTextBox1", true).FirstOrDefault() as RichTextBox;
rtb.Location = rtbold.Location;
rtb.Size = rtbold.Size;
targetControl.Controls.Add(rtb);
}
else if (c.GetType() == typeof(Label))
{
Label lbl = new Label();
lbl.Name = "label" + number;
Label lblold = this.Controls.Find("label1", true).FirstOrDefault() as Label;
lbl.Text = lblold.Text;
lbl.Location = lblold.Location;
lbl.Size = lblold.Size;
targetControl.Controls.Add(lbl);
}
else if (c.GetType() == typeof(TextBox))
{
TextBox tbox = new TextBox();
tbox.Name = "textBox" + number;
TextBox tboxold = this.Controls.Find("textBox1", true, FirstOrDefault() as TextBox;
tbox.Location = tboxold.Location;
tbox.Size = tboxold.Size;
targetControl.Controls.Add(tbox);
}
}
}
catch (Exception ex)
{
MessageBox.Show((ex.Message));
}
}
另外值得补充:
在下面的图片中,第一张图片位于tabPage1
的{{1}},第二张图片位于TabControl
的{{1}},其中tabPage2
位于TabControl
一切都很好,除了它看起来很丑:
例如,如果您点击flowLayoutPanel
,您会看到文字正确无误:
问题:我该如何解决这个问题?一切都会显示出来吗?
答案 0 :(得分:1)
有明显的腐败现象,所以你必须先调试一下这个问题。
您正在复制面板的所有属性(CopyControl中的Get / Set循环),这可能会导致一些奇怪的问题。此外,循环调用所有字段(甚至是只读字段)的get_,这可能会导致它自己的奇怪的东西。 (如果我正在调试这个问题,那个循环将是我改变的第一件事。)
当您解决'损坏'时,您可能想要重新访问复制按钮和其他控件的代码,您应该分配Dock和Anchor属性。没有它们,当第一次布局发生时,控件可能会“浮动”掉控件。