簡體   English   中英

C# 如何從 2nd Form 以 1st Form 創建 object

[英]C# how to create object in 1st Form from 2nd Form

我不清楚如何從第 2 形式在第 1 形式(主形式)中創建 object (屬性:帶有 label 和內部文本框的面板)。

  1. 第一種形式有一個面板,應在其中創建屬性
  2. 第一種形式也有一個打開第二種形式的按鈕
  3. 2nd Form 負責創建和配置屬性
  4. 第二種形式有按鈕- “創建”。 單擊時,它應該在 1st Form 中創建一個屬性並將其插入到Panel of Attributes中。

您能否提供一些示例如何執行此類操作?

主表格 第二種形式

為什么不讓Form1自己創建控件呢?

   public partial class Form1 : Form {

     public void CreateMyControl() {
       Panel attrPanel = new Panel() {
         Parent = this,
         Size = new Size(100, 60),   //TODO: Put the right value here
         Location = new Point(0, 0), //TODO: Put the right value here 
       };  

       new Label() {
         Parent   = attrPanel,         
         Text     = "I'm the Label", //TODO: Put the right value here
         Location = new Point(4, 4)  //TODO: Put the right value here
       };

       new TextBox() {
         Parent   = attrPanel, 
         Text     = "I'm the TextBox", //TODO: Put the right value here
         Location = new Point(4, 34)   //TODO: Put the right value here
       }    
    }

    private void btnRun_Click(object sender, EventArgs e) {
      // We create Form2 instance and pass current Form1 instance to it    
      Form2 form2 = new Form2(this);

      form2.ShowDialog(); // Or Show
    }

完成Form1后,讓我們通過構造函數將Form1傳遞給

public partial class Form2 : Form {
  ...

  public Form1 ParentForm {get;} = null;

  public Form2() {
    InitializeComponent();
  }

  public Form2(Form1 parentForm) : this() {
    ParentForm = parentForm;
  }

  private void btnCreateControl_Click(object sender, EventArgs e) {
    // If we have parent form, create some controls on it
    if (ParentForm != null)
      ParentForm.CreateMyControl(); 
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM