2012-09-07 30 views
0

我正在開發一個應用程序,它有許多面板,全部來自BasePanel用戶控件。
使用該應用程序與使用嚮導非常相似 - 每次在其他面板上方顯示不同面板時。
我想有一個計時器排序,所以當沒有用戶活動時,顯示第一個面板。在InitializeComponent之後調用基構造器

這裏是底板的代碼:

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_Click事件。

這是正常的繼承行爲,但仍然 - 我如何註冊派生類的控件在基類?

回答

0

這是最終解決這樣的: 我在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; 
} 
相關問題