2012-08-07 15 views
6

如果AutoEventWireup屬性設置爲false,則需要手動連接事件。但是,我似乎無法讓Page_PreInit開火。我猜想我可能會讓聯絡發生得太晚(一旦我們已經過去了Page_PreInit),但我不知道還有什麼地方需要佈線。手動連接Page_PreInit事件,AutoEventWireup設置爲false

例如...

protected override void OnInit(EventArgs e) 
{ 
    base.OnInit(e) 
    PreInit += new EventHandler(Page_PreInit); 
    Load += new EventHandler(Page_Load); 
} 

protected void Page_PreInit(object sender, EventArgs e) 
{ 
    Response.Write("Page_PreInit event fired!<br>"); //this is never reached 
} 

protected void Page_Load(object sender, EventArgs e) 
{ 
    Response.Write("Page_Load event fired!<br>"); 
} 

上面的代碼會導致 「Page_Load事件中被解僱了!」被顯示,但沒有從Page_PreInit。我在配對之前和之後嘗試了base.OnInit(e),並且沒有任何效果。

顯示的圖表here表示OnInit方法實際上是在PreInit事件之後出現的。考慮到這一點,我試圖壓倒OnPreInit並做同樣的事情---沒有效果。

MSDN文章here明確指出,如果AutoEventWireup設置爲false,事件可以通過覆蓋OnInit進行連接。他們使用的示例是Page_Load,當然,它的工作方式與我的工作方式類似,但他們沒有說明這似乎不適用於Page_PreInit事件。

我的問題是:如何將的Page_PreInit事件設置爲false

據我所知,MSDN page上列出了一些替代品,例如使用頁面的構造函數。我想知道如何去做,就像他們建議的OnInit一樣。

+0

你必須做在構造函數或在調用'base.OnInit'之前。 – Strelok 2012-08-07 08:07:37

+0

令人遺憾的是,將行放在base.OnInit(e)之上沒有任何效果,針對較早的事件(如OnPreInit)仍然無法達到Page_PreInit事件。 – CptSupermrkt 2012-08-07 08:10:07

回答

10

OnPreInit()方法的基本實現負責提高PreInit事件。由於你的覆蓋調用之前註冊你的PreInit處理程序,它確實不會被調用。

嘗試調用基類的方法後註冊的處理程序:

protected override void OnPreInit(EventArgs e) 
{ 
    PreInit += new EventHandler(Page_PreInit); 
    Load += new EventHandler(Page_Load); 

    // And only then: 
    base.OnPreInit(e); 
} 
+0

是的,它做到了。謝謝。 – CptSupermrkt 2012-08-08 00:19:13

+0

應該指出,這段代碼重寫'OnPreInit'而不是'OnInit'。 – Trisped 2013-03-21 23:05:42

0

在初始化區域添加的所有事件:

public WebName() 
     { 
     this.event+=TAB Key 
     } 
相關問題