无法访问事件

本文关键字:事件 访问 | 更新日期: 2023-09-27 18:37:12

我在从窗体订阅到用户控件中的事件时遇到问题。

主表单代码:

public partial class mainForm : Form
{
    public mainForm()
    {
        InitializeComponent();
        UserControl menuView = new mnlib.mnlibControl();
        newWindow(menuView);
    }
    public void newWindow(UserControl control)
    {
        this.mainPanel.Controls.Clear();
        this.mainPanel.Controls.Add(control);
    }
    mnlibControl.OnLearnClick += new EventHandler(ButtonClick); //Error in this line
    protected void ButtonClick(object sender, EventArgs e)
    {
         //handling..
    }
}

用户控制代码:

public partial class mnlibControl : UserControl
{
    public mnlibControl()
    {
        InitializeComponent();
    }
    private void btn_beenden_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    public event EventHandler LearnClick;
    private void btn_lernen_Click(object sender, EventArgs e)
    {
        if (this.LearnClick != null)
            this.LearnClick(this, e);
    }
}

现在,Visual Studio 标记了"mnlibControl.OnLearnClick ..."行为错误。"mnlibControl"将找不到,可能是缺少使用指令等。所有这些代码和两个窗体都位于同一个项目文件中。我尝试了一下,像地狱一样用谷歌搜索,但就是找不到解决我的问题的方法。

在 UserControl 窗体中有一个按钮 - 当它被单击时,它将触发 mainForm 中的 newWindow 方法并打开另一个窗口。

我的问题解决方案的来源是:如何在用户控件中创建事件并在主窗体中处理它?

无法访问事件

您的组件中没有OnLearnClick。您需要订阅LearnClick。您还需要订阅功能块。您还应该使用混凝土类型(mnlib.mnlibControl),而不是UserControl

public mainForm()
{
    InitializeComponent();
    mnlib.mnlibControl menuView = new mnlib.mnlibControl();
    menuView.LearnClick += new EventHandler(ButtonClick);
    newWindow(menuView);
}

您的代码mnlibControl.OnLearnClick += new EventHandler(ButtonClick);必须在任何功能块(即方法,属性等)中。

您必须将此

行放在实际方法中:

mnlibControl.LearnClick += new EventHandler(ButtonClick);

喜欢这个:

public mainForm()
{
    InitializeComponent();
    UserControl menuView = new mnlib.mnlibControl();
    newWindow(menuView);
    mnlibControl.OnLearnClick += new EventHandler(ButtonClick);
}