65.9K
CodeProject 正在变化。 阅读更多。
Home

动态向 ASP.NET 页面头部添加样式

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (3投票s)

2013年1月8日

CPOL

1分钟阅读

viewsIcon

78364

本技巧描述了如何将动态样式添加到 ASP.NET 页面头部。

引言

最近,在开发 ASP.NET 网站时,我希望能够动态地修改页面样式。我通过 Google 搜索发现有很多种实现方法。在本技巧中,我想与大家分享这些方法。

Using the Code

以下是一些实现此目的的方法:

1. 使用 Page.header.Controls.Add()

Page.Header 属性获取页面的文档头部,如果页面声明中定义了带有 “runat=server” 标签的 head 元素。Header 属性获取对 HtmlHead 对象的引用,你可以使用该对象设置页面的文档头部信息。HtmlHead 允许你添加诸如样式表、样式规则、标题和元数据等信息到 head 元素中。

你可以阅读更多关于 Page.Header 属性的信息 这里

通过使用字面量控件,你可以包含 CSS 文件,甚至是一组样式。

Literal cssFile = new Literal()
{
    Text = @"<link href=""" + Page.ResolveUrl(styleFilePath) + 
	@""" type=""text/css"" rel=""stylesheet""/>"
};
Page.Header.Controls.Add(cssFile);  
Page.Header.Controls.Add(
new LiteralControl(
@"<style type='text/css'>
        .myCssClass
        {
background: black;
border: 1px solid;
        }
</style>
    "
)); 

或者可以使用 HtmlGenericControl 来添加样式文件

//// Insert css file to header
HtmlGenericControl oCSS = oCSS = newHtmlGenericControl();
oCSS.TagName = "link";
oCSS.Attributes.Add("href", "css/mystyle.css");
oCSS.Attributes.Add("rel", "stylesheet");
oCSS.Attributes.Add("type", "text/css");
this.Page.Header.Controls.Add(oCSS);

2. Page.Header.Stylesheet

一种更优雅的技术是使用 Page.Header.Stylesheet。与其使用 string 来定义样式(如上面使用 Literal 的方法),你可以使用 style 属性来创建它。

//// Create dynamic style rule which applies to the CSS class selector (“.MyCssClass”)
Style dynamicClassStyle = new Style();
dynamicClassStyle.BorderStyle = BorderStyle.Solid;
dynamicClassStyle.BorderColor = System.Drawing.Color.Black;
dynamicClassStyle.BorderWidth = new Unit(1);
dynamicClassStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicClassStyle, null, ".MyCssClass"); 
 //// Create dynamic style rule which applies to type selector ("DIV")
Style dynamicTypeStyle = new Style();
dynamicTypeStyle.BorderStyle = BorderStyle.Solid;
dynamicTypeStyle.BorderColor = System.Drawing.Color.Black;
dynamicTypeStyle.BorderWidth = new Unit(1);
dynamicTypeStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicTypeStyle, null, "DIV"); 

有关更多信息,请参阅 此链接

无论你采用哪种技术,请记住以下提示:

在异步回发期间,使用 IStyleSheet 接口的方法以编程方式添加样式不受支持。当你将 AJAX 功能添加到 Web 页面时,异步回发会更新页面的区域,而不会更新整个页面。

© . All rights reserved.