C# - EventHandler始终为null

Bri*_*ooe 3 c# winforms

我试图在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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 5

你的问题在这里:

    private LoginUserControl login = new LoginUserControl();
    private CreateRecUserControl createRec = new CreateRecUserControl();

    public ApplicationContainer()
    {
        InitializeComponent();
        login.CreateButtonEvent += gotoCreate;
    }
Run Code Online (Sandbox Code Playgroud)

您正在LoginUserControl表单中创建一个变量并订阅它,但您尚未在任何地方将其添加到表单中.就像在,你没有地方Children.Add(login).

我猜你LoginUserControl在你的表单上有另外一份你放在设计器中的副本,那就是你在运行你的应用程序时要与之交互的副本.事件始终为空,因为您已在其他用户控件上订阅该事件.

转到设计器,单击用户控件,转到属性(F4),单击事件按钮,找到CreateButtonEvent并添加gotoCreate方法.

然后删除login您创建的成员变量,因为这只会令人困惑.

同样,与CreateRecUserControl.如果未在设计器中添加,请将其添加到设计器中并删除成员变量createRec.

在此输入图像描述