實際上,它必須設置在Page_PreInit
,如果您嘗試更改Page_Init
中的主題,它將不起作用。
最常見的解決方案是爲所有頁面使用父類。這是一次性更改,並將邏輯放在父類中。然後,您從繼承Page
而不是從ThemedPage
繼承。在課程ThemedPage
中,當然它自身繼承自Page
,您可以重寫Page.OnPreInit方法。
你問過「兩條線」,如果你移除雜亂的東西,它實際上是一條。這是VB:
Public Class ThemedPage
Inherits Page
Protected Overrides Sub OnPreInit(ByVal e As System.EventArgs)
Me.Theme = HttpContext.Current.Request.Url.Host.Replace(".com", "")
MyBase.OnPreInit(e)
End Sub
End Class
而不是這樣的:
Partial Class _Default
Inherits System.Web.UI.Page
你現在這樣寫:
Partial Class _Default
Inherits ThemedPage
這一切!一次性搜索/替換,你就完成了。爲了完整起見,這裏是相同的(只有級別)C#:
// C# version
using System.Web;
using System.Web.UI;
public class ThemedPage : Page
{
protected override void OnPreInit(System.EventArgs e)
{
this.Theme = HttpContext.Current.Request.Url.Host.Replace(".com", "");
base.OnPreInit(e);
}
}
更新:添加VB代碼示例
更新:增加C#代碼示例
注:主題必須存在,否則您會得到一個異常:Theme 'ThemeName' cannot be found in the application or global theme directories.
。如果您想要默認主題或無主題(如果主題不存在),請圍繞try
/catch
區塊進行包裝,並使用catch
區塊設置默認主題。
有趣的方法。 – 2009-10-21 11:07:13
謝謝,隊友...會嘗試應用它 – eugeneK 2009-10-21 11:17:19
太棒了,非常感謝你! :) – 2009-10-21 11:44:00