想象一个 ASP.NET 应用程序,其中定义了多个主题。如何动态更改整个应用程序的主题(不仅仅是单个页面)。我知道通过<pages Theme="Themename" />
in是可能的web.config
。但我希望能够动态地改变它。我应该怎么做?
提前致谢
您可以Page_PreInit
按照此处的说明执行此操作:
protected void Page_PreInit(object sender, EventArgs e)
{
switch (Request.QueryString["theme"])
{
case "Blue":
Page.Theme = "BlueTheme";
break;
case "Pink":
Page.Theme = "PinkTheme";
break;
}
}
这是一个很晚的答案,但我想你会喜欢这个的..
您可以在 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;
}
};
}
PreInit
为您的所有 asp.net 页面保留一个共同的基本页面,并在基本页面中之后或之前的任何事件之间修改主题属性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)
{
}
}