[英]Calling a Main function from a userControl
我需要从 userControl 从我的 Main 调用一个函数。 我试图将我的函数放在不起作用的静态中,因为在这个函数中我访问了主窗体的控件,所以我有一个错误:
属性、方法或非静态字段需要对象引用
这是我的代码:要调用的函数:
public void ShowSP(bool isClick, Projet projet)
{
if (isClick)
{
clearProjectPanel();
foreach (var sousProjet in projet.sousProjects)
{
int x = 0, y = 0;
UserControl_sousProjet userControl = new UserControl_sousProjet(sousProjet);
userControl.Location = new Point(x, y);
panel_projects.Controls.Add(userControl);
y += userControl.Height;
}
}
else
{
refreshProject();
}
}
我想打电话给他的地方:
private void label_projetName_Click(object sender, EventArgs e)
{
if(!isClick)
isClick = true;
else
isClick = false;
// Affiche / Enlève les sous projet d'un projet
Main.ShowSP(isClick, projet);
}
如果有解决方法谢谢
编辑 :
我不知道这是不是一个错误,但是当我说“主要”时,我的意思是一个表格!
对于不同的表单进行通信,您需要在子Form
声明一个事件,以便父Form
可以获取数据。
关于事件用法的官方文档,可以在这里找到
public event EventHandler<EventArgs> OnClick;
然后在您的父控件中
public void ShowSP(object sender, ThresholdReachedEventArgs e) {
// Access from e.isClick and e.projet
}
// Assign this whenever the child control is available.
childControl.OnClick += ShowSP;
再次在子控件中
private void label_projetName_Click(object sender, EventArgs e)
{
if(!isClick)
isClick = true;
else
isClick = false;
// Affiche / Enlève les sous projet d'un projet
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.isClick= isClick;
args.projet = projet;
OnClick(null, args);
}
只需将父表单中的方法设为公开,并在 UserControl 中创建主表单类型的属性:
public Main MainForm { get; set;} // add this to your user control (imagining that Main is Form class)
然后您可以在 UserControl 中访问它,例如:
MainForm.PulicMethodYouWantToCall();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.