Inheritance 在InitializeComponent之后调用基构造函数
我正在开发一个有许多面板的应用程序,所有面板都来自Inheritance 在InitializeComponent之后调用基构造函数,inheritance,constructor,derived-class,Inheritance,Constructor,Derived Class,我正在开发一个有许多面板的应用程序,所有面板都来自BasePanel用户控件。 使用应用程序与使用向导非常相似-每次在所有其他面板上方显示不同的面板时。 我想要一个计时器,这样当没有用户活动时,第一个面板就会显示出来 以下是基本面板代码: public partial class BasePanel : UserControl { private Timer timer = new Timer(); public BasePanel() { Initia
BasePanel
用户控件。使用应用程序与使用向导非常相似-每次在所有其他面板上方显示不同的面板时。
我想要一个计时器,这样当没有用户活动时,第一个面板就会显示出来 以下是基本面板代码:
public partial class BasePanel : UserControl
{
private Timer timer = new Timer();
public BasePanel()
{
InitializeComponent();
timer.Interval = 5000;
timer.Tick += timer_Tick;
foreach (Control control in Controls)
control.Click += Control_Click;
}
public event EventHandler NoActivity = delegate { };
private void timer_Tick(object sender, EventArgs e)
{
NoActivity(this, EventArgs.Empty);
}
private void Control_Click(object sender, EventArgs e)
{
timer.Stop();
timer.Start();
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
timer.Start();
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
timer.Stop();
}
}
问题:在调用派生的
InitializeComponent()
之前,将调用BasePanel
构造函数。由于
BasePanel
本身没有控件-因此没有控件注册到control\u Click
事件
这是正常的继承行为,但仍然-如何在基类注册派生类的控件 这最终是这样解决的: 我在
BasePanel
中添加了这个递归函数:
public void RegisterControls(Control parent)
{
foreach (Control control in parent.Controls)
{
control.Click += Control_Click;
RegisterControls(control);
}
}
在创建这些面板的类中:
private static T CreatePanel<T>()
{
T panel = Activator.CreateInstance<T>();
BasePanel basePanel = panel as BasePanel;
if (basePanel != null)
{
basePanel.BackColor = Color.Transparent;
basePanel.Dock = DockStyle.Fill;
basePanel.Font = new Font("Arial", 20.25F, FontStyle.Bold, GraphicsUnit.Point, 0);
basePanel.Margin = new Padding(0);
basePanel.RegisterControls(basePanel);
}
return panel;
}
private static T CreatePanel()
{
T panel=Activator.CreateInstance();
基板基板=作为基板的面板;
if(basePanel!=null)
{
basePanel.BackColor=Color.Transparent;
basePanel.Dock=DockStyle.Fill;
basePanel.Font=新字体(“Arial”,20.25F,FontStyle.Bold,GraphicsUnit.Point,0);
basePanel.Margin=新填充(0);
基板。寄存器控制(基板);
}
返回面板;
}