首页 > 解决方案 > 如何将按钮从子窗体动态添加到主窗体

问题描述

当我选择了位于另一个表单Button上的项目时,我想在我的主表单上添加一个功能。ListView

下面的代码我已经放在ListView表单上,​​但我不确定我做对了,因为当项目被选中时没有任何反应。

Point newLoc = new Point(5,5);  

Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);

标签: c#winforms

解决方案


首先,您必须找到主表单(假设您正在使用WinForms):

 using System.Linq;

 ...

 //TODO: Put the right type instead of MyMainForm
 MyMainForm mainForm = Application
   .OpenForms
   .OfType<MyMainForm>()
   .LastOrDefault();      // If there many opened main forms, let's use the last one

然后如果找到表单,让我们添加一个按钮:

public partial class MyChildForm : Form {
  // It seems it should be a field to store the next button position
  private Point newLoc = new Point(5, 5);  

  private Button addButtonToMainForm() {
    //TODO: Put the right type instead of MyMainForm
    MyMainForm mainForm = Application
     .OpenForms
     .OfType<MyMainForm>()
     .LastOrDefault();    

    // If Main Form has been found, let's add a button on it
    if (mainForm != null) {
      Button b = new Button() {
        Size     = new Size(10, 50), 
        Location = newLoc,
        Parent   = mainForm, // Place the button on mainForm
      }

      newLoc.Offset(0, b.Height + 5);

      return b;
    }

    return null;
  }

  private void myListView_ItemSelectionChanged(object sender,
                                               ListViewItemSelectionChangedEventArgs e) {
    // If item selected (not unselected) 
    if (e.Item.Selected) {
      //TODO: Some other conditions which on the item that has been selected 
      // Button on the Main Form, null if it hasn;t been created
      Button createdButton = addButtonToMainForm();
    }
  }
  ...

推荐阅读