如何在运行时以编程方式更改asp webapplication主题(而不是页面)?

时间:2012-01-26 14:56:06

标签: c# asp.net themes

我正在学习ASP.net,我一直在玩主题和母版页。我决定改变网站的主题,并使用web.config解决方案(将主题添加到web.config)。我现在要做的是能够根据用户和用户选择的主题更改主题。

我一直无法找到任何教程,所有这些教程似乎都展示了如何更改单独的内容页面,但我想更改整个网站主题。

你如何以最简单的方式做到这一点?我没有连接到数据库atm。它只是为了练习:)

亲切的问候

3 个答案:

答案 0 :(得分:2)

创建一个您继承所有页面的基页,并在OnPreInit事件中设置主题:

public class ThemePage : System.Web.UI.Page
{
    protected override void OnPreInit(EventArgs e)
    {
        SetTheme();            

        base.OnPreInit(e);
    }

    private void SetTheme()
    {
        this.Theme = ThemeSwitcher.GetCurrentTheme();
    }
}

以下是ThemeSwitcher实用程序类,用于处理获取/保存当前主题和列出主题。既然你说你没有使用数据库,你可以使用Session:

public class ThemeSwitcher
{
    private const string ThemeSessionKey = "theme";

    public static string GetCurrentTheme()
    {
        var theme = HttpContext.Current.Session[ThemeSessionKey]
            as string;

        return theme ?? "Default";
    }

    public static void SaveCurrentTheme(string theme)
    {
        HttpContext.Current.Session[ThemeSessionKey]
            = theme;
    }

    public static string[] ListThemes()
    {
        return (from d in Directory.GetDirectories(HttpContext.Current.Server.MapPath("~/app_themes"))
                select Path.GetFileName(d)).ToArray();
    }
}

您需要一个可以更改主题的页面。添加一个包含以下代码的下拉列表:

public partial class _Default : ThemePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        }
    }

    private void BindData()
    {
        var currentTheme = ThemeSwitcher.GetCurrentTheme();

        foreach (var theme in ThemeSwitcher.ListThemes())
        {
            var item = new ListItem(theme);
            item.Selected = theme == currentTheme;
            ddlThemes.Items.Add(item);
        }
    }

    protected void ddlThemes_SelectedIndexChanged(object sender, EventArgs e)
    {
        ThemeSwitcher.SaveCurrentTheme(ddlThemes.SelectedItem.Value);
        Response.Redirect("~/default.aspx");
    }       
}

您可以下载示例应用here

答案 1 :(得分:1)

我之前通过从基页继承所有页面

看到了这一点
    public partial class _Default : BasePage

并在基页类中设置主题。

public class BasePage : System.Web.UI.Page
{
  protected override void OnPreInit(EventArgs e)
  {
       base.OnPreInit(e);
       Page.Theme = //Your theme;
  }
}

答案 2 :(得分:1)

看看这些有用的MSDN文档:

Walkthrough: Creating User-Selectable Themes

How to: Apply ASP.NET Themes Programmatically

检查一下:

Master Pages and Themes

Scoping Themes

  

您无法直接将ASP.NET主题应用于母版页。如果你   在@ Master指令中添加一个主题属性,该页面将引发   它运行时出错。