【发布时间】:2016-02-22 17:49:48
【问题描述】:
我正在尝试在 UserControl 和 Form 之间实现一个非常基本的 EventHandler。关于订阅活动,我做错了什么?无论我尝试什么, CreateButtonEvent 始终为空。我最初试图在两个 UserControl 类之间执行此操作,但在假设 UserControl 订阅可能是问题的情况下决定使用 Form 作为订阅者。我也尝试过使用委托,但没有成功。
我已经在这个站点上查看并实施了无数解决方案来解决这个完全相同的问题,但我仍然无法让 Form 类订阅 UserControl 类中的事件。我确信这是一个非常简单的错误,我无法挑出。谁能给我一些见解?
这是 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");
}
}
}
这是表单类
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();
}
}
}
【问题讨论】:
-
从哪里调用 mehog goToCreate 在您的用户控制中?
-
不,根据您显示的代码,事件已正确连接。奇怪的是,
gotoCreate上的LoginUserControl本身看起来就像一个 EventHandler。您必须显示更多代码才能获得帮助(例如如何在表单上显示LoginUserControl)。 -
@Jonesopolis 你的意思是用户控件在表单中的可视化表示吗?
-
您确定订阅了正确的 LoginUserControl 吗?我想知道您的表单中是否还有另一个 LoginUserControl,可能在 ApplicationContainer.Designer.cs 中定义?