我們在做一個項目時有時候需要動態改變所有頁面的樣式,但當我們在Page指令或者Web.Config裡設定Theme時有一個問題,我無法通過程式動態且一致改變所有頁面的樣式,推薦一個方法,就是改寫OnPreInit事件,在App_Code裡建立一個PageBase類,他繼承自System.Web.UI.Page,然後所有頁面再繼承自PageBase,就搞定了,具體實現就自己看吧:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// PageBase 的摘要說明
/// </summary>
public class PageBase:System.Web.UI.Page
{
public PageBase()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Request.Cookies["skin"] != null && Request.QueryString["skin"] == null)
{
Page.Theme = Request.Cookies["skin"].Value.ToString();
}
else
{
if (Request.QueryString["skin"] != null)
{
HttpCookie c = new HttpCookie("skin", Request.QueryString["skin"]);
Response.Cookies.Add(c);
Page.Theme = Request.Cookies["skin"].Value.ToString();
}
else
Page.Theme = "skin";
}
}
}