想象一下在其中定义了几个主题的ASP.NET应用程序。我怎样才能动态地改变整个应用程序的主题(不只是一个页面)。我知道这可以通过<pages Theme="Themename" />
在web.config
。但我希望能够动态地改变它。我做得怎么样?如何动态更改总ASP.NET应用程序的主题?
由于提前
想象一下在其中定义了几个主题的ASP.NET应用程序。我怎样才能动态地改变整个应用程序的主题(不只是一个页面)。我知道这可以通过<pages Theme="Themename" />
在web.config
。但我希望能够动态地改变它。我做得怎么样?如何动态更改总ASP.NET应用程序的主题?
由于提前
您可以在Page_PreInit
as explained here做到这一点:
protected void Page_PreInit(object sender, EventArgs e)
{
switch (Request.QueryString["theme"])
{
case "Blue":
Page.Theme = "BlueTheme";
break;
case "Pink":
Page.Theme = "PinkTheme";
break;
}
}
保持您的所有asp.net页面的共同基页和PreInit
后或在基本页面的Page_Load
之前修改任何事件的主题属性。这将强制每个页面应用该主题。正如在这个例子中,将MyPage作为所有你的asp.net页面的基本页面。
public class MyPage : System.Web.UI.Page
{
/// <summary>
/// Initializes a new instance of the Page class.
/// </summary>
public Page()
{
this.Init += new EventHandler(this.Page_Init);
}
private void Page_Init(object sender, EventArgs e)
{
try
{
this.Theme = "YourTheme"; // It can also come from AppSettings.
}
catch
{
//handle the situation gracefully.
}
}
}
//in your asp.net page code-behind
public partial class contact : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
不要在Page_Load中做这个,而是在'PreInit'中。 – 2010-06-23 06:56:26
没错。更新了答案。谢谢。 – 2010-06-23 07:02:26
这是一个非常晚的答案,但我想你会喜欢这个..
您可以更改页的主题在PreInit事件中,但您没有使用基本页面。
在masterpage中创建一个名为ddlTema的下拉列表,然后在Global.asax中写入此代码块。看看魔法是如何工作的:)
public class Global : System.Web.HttpApplication
{
protected void Application_PostMapRequestHandler(object sender, EventArgs e)
{
Page activePage = HttpContext.Current.Handler as Page;
if (activePage == null)
{
return;
}
activePage.PreInit
+= (s, ea) =>
{
string selectedTheme = HttpContext.Current.Session["SelectedTheme"] as string;
if (Request.Form["ctl00$ddlTema"] != null)
{
HttpContext.Current.Session["SelectedTheme"]
= activePage.Theme = Request.Form["ctl00$ddlTema"];
}
else if (selectedTheme != null)
{
activePage.Theme = selectedTheme;
}
};
}
@ this。 __curious_geek,为什么更喜欢在Page_Load中做,而不是Pre_Int? – 2010-06-23 07:02:41