2010-06-23 84 views
5

想象一下在其中定義了幾個主題的ASP.NET應用程序。我怎樣才能動態地改變整個應用程序的主題(不只是一個頁面)。我知道這可以通過<pages Theme="Themename" />web.config。但我希望能夠動態地改變它。我做得怎麼樣?如何動態更改總ASP.NET應用程序的主題?

由於提前

回答

6

您可以在Page_PreInitas 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; 
    } 
} 
+0

@ this。 __curious_geek,爲什麼更喜歡在Page_Load中做,而不是Pre_Int? – 2010-06-23 07:02:41

1

保持您的所有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) 
    { 

    } 
} 
+0

不要在Page_Load中做這個,而是在'PreInit'中。 – 2010-06-23 06:56:26

+0

沒錯。更新了答案。謝謝。 – 2010-06-23 07:02:26

3

這是一個非常晚的答案,但我想你會喜歡這個..

您可以更改頁的主題在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; 
       } 

      }; 
    } 
相關問題