C# 如何从内容页面背后的代码更改母版页的背景?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change the background of a masterpage from the code behind of a content page?
提问by Bryan Denny
I specifically want to add the style of background-color
to the <body>
tag of a master page, from the code behind (C#) of a content page that uses that master page.
我特别想从使用该母版页的内容页的隐藏代码 (C#)中将 的样式添加background-color
到<body>
母版页的标记中。
I have different content pages that need to make the master page has different colors depending on which content page is loaded, so that the master page matches the content page's theme.
我有不同的内容页面,需要根据加载的内容页面使母版页具有不同的颜色,以便母版页与内容页的主题相匹配。
I have a solution below:
我在下面有一个解决方案:
I'm looking for something more like:
我正在寻找更像的东西:
Master.Attributes.Add("style", "background-color: 2e6095");
Inside of the page load function of the content page. But I can't get the above line to work. I only need to change the background-color
for the <body>
tag of the page.
内容页面的页面加载功能内部。但我无法让上面的线路工作。我只需要更改页面background-color
的<body>
标签。
采纳答案by Adhip Gupta
What I would do for the particular case is:
我会为特定情况做的是:
i. Define the body as a server side control
一世。将主体定义为服务器端控件
<body runat="server" id="masterpageBody">
ii. In your content aspx page, register the MasterPage with the register:
ii. 在您的内容 aspx 页面中,使用 register 注册 MasterPage:
<% MasterPageFile="..." %>
iii. In the Content Page, you can now simply use
三、在内容页面中,您现在可以简单地使用
Master.FindControl("masterpageBody")
and have access to the control. Now, you can change whatever properties/style that you like!
并有权访问该控件。现在,您可以更改您喜欢的任何属性/样式!
回答by GateKiller
I believe you are talking about a content management system. The way I have delt with this situation in the past is to either:
我相信您在谈论内容管理系统。我过去处理这种情况的方式是:
- Allow a page/content to define an extra custom stylesheet or
- Allow a page/content to define inline style tags
- 允许页面/内容定义额外的自定义样式表或
- 允许页面/内容定义内联样式标签
回答by Bryan Denny
This is what I came up with:
这就是我想出的:
In the page load function:
在页面加载功能中:
HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("default_body");
body.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#2E6095");
Where
在哪里
default_body = the id of the body tag.
default_body = body 标签的 id。