如何在表单之间共享事件处理程序 [英] How to share an event handler between forms
问题描述
我有一个Form1.button1和Form2.button1.我希望两个按钮在单击时共享相同的事件处理程序.请参阅form2.button1_Click事件处理程序中的注释.
I have a Form1.button1 and Form2.button1. I would like to have both buttons share the same event handler for when they are clicked. See comments in the form2.button1_Click event handler.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Hello World";
}
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
}
Form2
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
}
private void button1_Click(object sender, EventArgs e)
{
// how do I get the form2.button1_Click and the form1.button1_Click
// to share the same event handler?
}
}
任何有关如何在表单之间进行通信的常规资源也将不胜感激.我目前所要做的就是将变量和方法设置为public,并将表单传递给其他表单.
Any general resources for how to communicate between forms would also be greatly appreciated. All I currently know to do is set variables and methods as public and pass forms to other forms.
推荐答案
如果要将事件处理仅单源提供给一种方法,则需要更改其中一个按钮订阅事件的方式.一种快速的方法如下:
If you want to single-source the event handling to just one method, then you'll need to change how the event is subscribed to by one of the buttons. A quick way to do this is the following:
- 在
Form1
中,将button1_Click()
public
替换为private
. -
在
Form2
中,将以下行添加到构造函数中:
- In
Form1
, makebutton1_Click()
public
instead ofprivate
. In
Form2
, add the following line to the constructor:
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
this.button1.Click += new EventHandler(this.form1.button1_Click);
}
这篇关于如何在表单之间共享事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!