C# 从自定义控件调用父控件
我有一个表单,这个表单上有一个flowlayoutpanel,其中有多个定制的文本框 表单将重写基本methode Refresh(),以执行其他一些操作。 现在,我正在深入了解家长,以便最终进入表单并进行刷新C# 从自定义控件调用父控件,c#,winforms,C#,Winforms,我有一个表单,这个表单上有一个flowlayoutpanel,其中有多个定制的文本框 表单将重写基本methode Refresh(),以执行其他一些操作。 现在,我正在深入了解家长,以便最终进入表单并进行刷新 this.Parent.Parent.Parent.Refresh(); 我想在其他表单上重复使用控件,那么有其他方法吗 我知道有一段时间(真的)是可能的: Boolean diggToParent = true; var parent = this.Parent; while (d
this.Parent.Parent.Parent.Refresh();
我想在其他表单上重复使用控件,那么有其他方法吗
我知道有一段时间(真的)是可能的:
Boolean diggToParent = true;
var parent = this.Parent;
while (diggToParent)
{
if (parent.Parent != null)
{
parent = parent.Parent;
}
else
break;
}
parent.Refresh();
但是有没有更干净的方法可以做到这一点呢?您可以通过创建并引发一个由父窗体处理的事件来解决这个问题:
public class MyUserControl : UserControl
{
// ...
public event EventHandler RequestRefresh;
// Call this method whenever you want the parent to refresh
private void OnRequestRefresh()
{
if (RequestRefresh != null)
RequestRefresh(this, EventArgs.Empty);
}
}
在父窗体(或应刷新的容器)中,添加事件处理程序,例如
public class MyParentForm : Form
{
public MyParentForm()
{
InitializeComponent();
userCtrl.RequestRefresh += userCtrl_RequestRefresh;
}
// Do whatever the parent thinks is necessary to refresh.
public void userCtrl_RequestRefresh(object sender, EventArgs e)
{
Refresh();
}
// ...
}
这样,当用户控件请求刷新时,父窗体可以决定执行什么操作。有关事件的详细信息,请参见。Ofcours,未考虑使用事件