无法访问事件

时间:2015-01-10 15:26:17

标签: c# winforms user-controls

我遇到了从表单订阅到用户控件中的事件的问题。

的MainForm码:

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”,也许缺少使用指令等。 所有这些代码和两个表单都位于同一个项目文件中。 我试着用Google搜索,但是找不到解决问题的方法。

在UserControl表单中有一个按钮 - 当它的clicket它将触发mainForm中的newWindow方法并打开另一个窗口。

我的问题解决方案的来源是:How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您必须将此行放在实际方法中:

mnlibControl.LearnClick += new EventHandler(ButtonClick);

像这样:

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