C# 如何在动态母版页中应用主题?

C# 如何在动态母版页中应用主题?,c#,asp.net,C#,Asp.net,母版页中是否有重写PreInit?或者母版页中是否可以继承PreInit?您不能直接将ASP.NET主题应用于母版页。如果将主题属性添加到@Master指令,则页面在运行时将引发错误 但是,在以下情况下,主题适用于母版页: 如果在内容页中定义了主题。母版页在内容页的上下文中解析,因此内容页的主题也应用于母版页 如果所有页面都有一个基本页面类,则可以应用以下内容: public partial class SiteMaster : System.Web.UI.MasterPage { pr

母版页中是否有重写PreInit?或者母版页中是否可以继承PreInit?

您不能直接将ASP.NET主题应用于母版页。如果将主题属性添加到@Master指令,则页面在运行时将引发错误

但是,在以下情况下,主题适用于母版页:


如果在内容页中定义了主题。母版页在内容页的上下文中解析,因此内容页的主题也应用于母版页

如果所有页面都有一个基本页面类,则可以应用以下内容:

public partial class SiteMaster : System.Web.UI.MasterPage
{
    private string _theme = "Custom";
    public string Theme
    {
        get { return _theme; }
        set { _theme = value; }
    }
}

public class BasePage : System.Web.UI.Page
{
    protected void Page_PreInit(object  sender, EventArgs e)
    {
        var siteMaster = this.Master as SiteMaster;
        if (siteMaster != null && !string.IsNullOrEmpty(siteMaster.Theme))
        {
            Theme = siteMaster.Theme;
        }
    }
}