将方法传递给新表单的控件

时间:2018-05-31 06:15:09

标签: c# winforms methods

所以我有两种形式: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);
    }
}

在上面的代码中,您可以明白我的观点。使用控件的表单,我将在创建该表单时为传递函数分配Eventhandlers。

我没有尝试任何东西,因为我不知道如何将方法传递给形式。

1 个答案:

答案 0 :(得分:3)

试试这个:

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;
    }
}