1

我有两种形式,我使用以下方法创建第二个:

Form2 f2 = new Form2();
f2.Show();

Form2有一个公开的变量,每次鼠标移动都会改变。我在该表单上有一个按钮,按下时可以保存变量。现在的问题是我不知道如何将其传递回Form1.

4

1 回答 1

1

你应该使用事件。 Form2应该定义一个适当触发的事件(听起来应该是单击按钮时)。 Form1然后可以订阅该事件并做......不管它。

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public event Action<string> MyEvent; //TODO give better name and set arguments for the Action

    private void button1_Click(object sender, EventArgs e)
    {
        string someValue = "Hello World!";  //TODO get value that you want to share

        if (MyEvent != null)
        {
            MyEvent(someValue);
        }
    }
}

然后在你的主要形式:

private void button1_Click(object sender, EventArgs e)
{
    Form2 otherForm = new Form2();

    //subscribe to the event.  You could use a real method here, rather than an anonymous one, but I prefer doing it this way.
    otherForm.MyEvent += value =>
    {
        //do other stuff with "value".
        label1.Text = value;
    };

    otherForm.Show();
}
于 2012-11-01T17:17:36.533 回答