实际上,它必须设置在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