我尝试将事件从一个userControl使用到一个表单,但是当我在表单构造函数中创建它时,我遇到了一个问题。我不知道失败在哪里。这是我的密码。
UserControl
public GameField()
{
InitializeComponent();
button.Click += Button_Clicked;
}
public event EventHandler ButtonClicked;
private void Button_Clicked(object sender, EventArgs e)
{
if (this.ButtonClicked != null) this.ButtonClicked(sender, e);
}表格
GameField gameField = new GameField(); //Instance of the derived class UserControl
public Form1()
{
InitializeComponent();
gameField.ButtonClicked += new EventHandler(this.btn_Click);
}
private void btn_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}有一个问题,在这里输入图像描述
发布于 2017-09-29 04:43:28
我想你想订阅Button_Clicked而不是ButtonClicked in GameField。
button.Click += Button_Clicked;编辑
我知道,我有一个预感,您有两个GameField实例。您通过表单设计器添加的一个,可能名为gameField1,以及您在代码中添加到表单中的那个名为gameField。
如果你打开Form1.Designer.cs,你能在里面看到一个gameField1 (或者你通过设计器添加它时给它起的任何名字)吗?
你能试一试以下几点吗?
gameField1.ButtonClicked += new EventHandler(btn_Clicked); // name can be other than gameField1, gameField1 is just the automatically generated name by VShttps://stackoverflow.com/questions/46481422
复制相似问题