【问题标题】:Copying a Control between forms moves it instead在表单之间复制控件会移动它
【发布时间】:2016-04-12 00:25:00
【问题描述】:

我正在 VS 2015 中编写一个 Windows 窗体应用程序。

我有一部分表单要根据单选选项进行更改。我要更改的部分放在 Panel 控件中。

我目前的计划是在另一个表单上创建 4 个控件布局。我创建了 Form2 并在其上创建了 4 个面板。当单击单选按钮时,我想将这些面板中的内容从 Form2 复制到 Form1 中的面板。

目前,当我单击每个单选按钮时,Form2 面板中的控件消失了!他们可能正在被移动,而不是被复制。我点击的第一个确实出现在表格 1 上,但其他的没有出现在第一个之后。我根本不想更改 Form2 (RefPanels)。我只想将那里的内容复制到 Form1。这是我正在尝试的代码。

//RefPanels is my Form2 instance.
public Form2 RefPanels = new Form2();

//Each Radiobutton has something similar to this.
RadioBtn1_CheckChanged(...)
{
  Control[] cArray = new Control[20];
  RefPanels.Panel1.Controls.CopyTo(cArray, 0);

  foreach (Control c in cArray)
  {
    Form1_Destination_Panel.Controls.Add(c);
  }
}

我确定我做错了。你能帮忙吗?

【问题讨论】:

  • Controls.CopyTo 不进行深度复制,仅复制对控件的引用。这就是它们移动的原因 - 当您将它们添加到目标面板时,您正在添加退出控件。

标签: c# winforms


【解决方案1】:

您只是将引用复制到您的控件。但是一个控件只能以一种形式使用。因此,控件以“旧”形式消失。您需要控件的真实副本。

This Question 描述了一种通过反射复制控件的方法。试试这样的解决方案:

private void copyControl(Control sourceControl, Control targetControl)
{
    // 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);
        }
    }
}

【讨论】:

  • 谢谢!我有一种感觉,这就是正在发生的事情......但你的链接答案有助于澄清
【解决方案2】:

我将通过为每个包含所需布局的控件的面板创建一个用户控件来实现这一点。然后,当您选择不同的布局时,您可以创建所需用户控件类的新实例并将其添加到正确的容器中。这也将允许您保留控件的方法等。

【讨论】:

  • 在 UC 中也添加一个 copyData(myUCclass sourceUC) 函数,这样你就可以从源 UC 中填写数据了..
猜你喜欢
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多