C# Can';中的t访问事件
我在从表单订阅用户控件中的事件时遇到问题 主窗体代码:C# Can';中的t访问事件,c#,winforms,user-controls,C#,Winforms,User Controls,我在从表单订阅用户控件中的事件时遇到问题 主窗体代码: public partial class mainForm : Form { public mainForm() { InitializeComponent(); UserControl menuView = new mnlib.mnlibControl(); newWindow(menuView); } public void newWindow(UserC
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”,可能是缺少using指令等。
所有这些代码和两个表单都位于同一个项目文件中。
我四处尝试,谷歌搜索,但就是找不到解决问题的方法
在UserControl表单中有一个按钮-当点击它时,它将触发Main表单中的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(按钮单击)代码>必须位于任何功能块(即方法、属性等)内。您必须将此行置于实际方法内:
mnlibControl.LearnClick += new EventHandler(ButtonClick);
像这样:
public mainForm()
{
InitializeComponent();
UserControl menuView = new mnlib.mnlibControl();
newWindow(menuView);
mnlibControl.OnLearnClick += new EventHandler(ButtonClick);
}
这样它告诉我,mnlibControl将不在实际上下文中:/@dncrftmnlibControl
是一个类名。您必须使用实例。我的意思是,表单中用户控件的ID是多少?在第5行的“LearnClick”之前,它一直工作。它说LearnClick没有定义。@dncrft您需要使用mnlib.mnlibControl
而不是UserControl
。请参阅更新的答案了解详细信息最后,这是有效的!非常感谢。不知道为什么我使用UserControl而不是mnlib.mnlibControl。。有点愚蠢;)同样在本例中,当我将代码放在mainForm括号中时,它表示在mnlib.mnlibControl中没有OnLearnClick的定义。如果我将“OnLearnClick”更改为“LearnClick”,它会显示,我需要“mnlib.mnlibControl.LearnClick”的对象引用