2013-10-20 56 views
1

我正在創建基於原型的表單應用程序,其中將有一個基本模板用於所有表單。模板中有一個方法,在構造控件時需要用實際的表單調用。從InitializeComponent調用基類方法

Form1.cs中:

public partial class Form1 : FormBase 
{ 
    public Form1():base() 
    { 
     InitializeComponent(); 
    } 
    ... 

Form1.Designer.cs:

private void InitializeComponent() 
{ 
    this.lblName = new MLabel(); 
    this.fldName = new MTextBox(); 
    this.lblUserID = new MLabel(); 
    this.fldUserID = new MTextBox(); 

    this.SuspendLayout(); 

    this.AddControl(lblName, fldName); 
    this.AddControl(lblUserID, fldUserID); 

FormBase.cs:

public partial class FormBase : Form 
{ 
    public FormBase() 
    { 
     InitializeComponent(); 
    } 
    protected void AddControl(Label lbl, Control ctrl) 
    { 
     //do something 
    } 
    ... 

,沒有編譯錯誤,但是當我打開在IDE中的Form1設計,它說沒有找到FormBase.AddControl。即使我運行該應用程序,該方法似乎也沒有被調用。

謝謝。

+1

** **從不在編輯在InitializeComponent()的代碼。當設計人員重寫方法時,您將丟失更改,或者在無法分析您的更改時彈出設計器。 –

回答

1

嘗試從Form1.cs中調用該方法的AddControl,不要從Form1.Designer.cs

叫它請讓我知道如果這樣還是失敗了。 :)

+0

我試圖從設計師那裏打電話的原因是我可以在IDE中看到設計,這樣我就可以輕鬆地進行更改。無論如何,我會檢查從表單調用。 –

+0

哦,那麼你想要什麼來替換Form1.Designer.cs的InitializeComponent方法中的一些自動生成的部分適當與您的模板? – Aditya

+0

不建議將代碼放置在InitializeComponent方法中,因爲當您使用設計器UI進行遊戲時,它會自動替換。 – Aditya

0

這是第二替代:

只是改變這部分

protected void AddControl(Label lbl, Control ctrl) 
{ 
    //do something 
} 

成這樣:

public void AddControl(Label lbl, Control ctrl) 
{ 
    //do something 
}