[英]C# - EventHandler is always null
我试图在UserControl和Form之间实现一个非常基本的EventHandler。 订阅活动我做错了什么? 无论我尝试什么,CreateButtonEvent始终为null。 我原本试图在两个UserControl类之间执行此操作,但在假设UserControl订阅可能是问题的情况下决定使用Form作为订阅者。 我也试过使用代表,没有成功。
我已经在这个网站上查看并实现了无数的解决方案,我仍然无法让Form类订阅UserControl类中的Event。 我确信这是一个非常简单的错误,我无法挑选出来。 谁能给我一些见解?
这是UserControl类
using System;
using System.Windows.Forms;
namespace SequenceAutomation
{
public partial class LoginUserControl : UserControl
{
public event EventHandler CreateButtonEvent;
public LoginUserControl()
{
InitializeComponent();
}
protected void gotoCreate(object sender, EventArgs e)
{
if (CreateButtonEvent != null)
CreateButtonEvent(this, e);
else
Console.WriteLine("CreateButtonEvent is null");
}
}
}
这是Form类
using System;
using System.Windows.Forms;
namespace SequenceAutomation
{
public partial class ApplicationContainer : Form
{
private LoginUserControl login = new LoginUserControl();
private CreateRecUserControl createRec = new CreateRecUserControl();
public ApplicationContainer()
{
InitializeComponent();
login.CreateButtonEvent += gotoCreate;
}
protected void gotoCreate(object sender, EventArgs e)
{
login.Hide();
createRec.Show();
}
}
}
你的问题在这里:
private LoginUserControl login = new LoginUserControl();
private CreateRecUserControl createRec = new CreateRecUserControl();
public ApplicationContainer()
{
InitializeComponent();
login.CreateButtonEvent += gotoCreate;
}
您正在创建一个LoginUserControl
作为表单中的变量并订阅它,但您尚未在任何地方将其添加到表单中。 在,你没有Children.Add(login)
。
我猜你在表单上有另一个LoginUserControl
副本放在设计器中,那就是你在运行应用程序时要与之交互的副本。 事件始终为空,因为您已在其他用户控件上订阅该事件。
转到设计器,单击用户控件,转到属性(F4),单击事件按钮,找到CreateButtonEvent
并添加gotoCreate
方法。
然后删除您创建的成员变量login
,因为这只会令人困惑。
此外,与CreateRecUserControl
相同。 如果它未在设计器中添加,请将其添加到设计器中并删除成员变量createRec
。
我完全测试你的代码并且没问题。 我认为这可能是这个错误之一:
1:此代码永远不会运行:
public ApplicationContainer() { InitializeComponent(); login.CreateButtonEvent += gotoCreate; }
或者2:你把代码放在代码中的某个地方:
login.CreateButtonEvent - = gotoCreate;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.