【问题标题】:Pass method to new form's control将方法传递给新表单的控件
【发布时间】:2018-05-31 06:15:09
【问题描述】:

所以我有两种形式:Form1Form2

Form1 我有这个代码:

pubilc class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Button1_Click(object sender, EventArgs e)
    {
        Form2 newForm = new Form2(); //Here i want to pass MyFunction
    }

    public void MyFunction()
    {
        MessageBox.Show("This is passed function from " + this.Text);
    }
}

Form2 我有这个:

public class Form2 : Form
{
    public Form2() //Here i want to receive Form1.MyFunction
    {
        InitializeComponent();
        this.Button1.Click += new System.EventHandler(passedFunction);
    }
}

在上面的代码中你可以明白我的意思。拥有带有控件的表单,在创建该表单时,我将为其分配具有传递函数的事件处理程序。

我没有尝试过任何事情,因为我不知道如何将方法传递给表单。

【问题讨论】:

标签: c# winforms methods


【解决方案1】:

试试这个:

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Button1_Click(object sender, EventArgs e)
    {
        Form2 newForm = new Form2(MyFunction); //Here i want to pass MyFunction
    }

    public void MyFunction(object sender, EventArgs e)
    {
        MessageBox.Show("This is passed function from " + this.Text);
    }
}

public class Form2 : Form
{
    public Form2(EventHandler passedFunction) //Here i want to receive Form1.MyFunction
    {
        InitializeComponent();
        this.Button1.Click += passedFunction;
    }
}

【讨论】:

  • 不敢相信这么简单。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多