我需要从自定义控件中添加到页面。我不能使用样式表 (.css),因为我使用的是 url(...) 并且需要解析 url。
现在我正在做:
Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>"));
但我希望有一些更优雅的东西?
我需要从自定义控件中添加到页面。我不能使用样式表 (.css),因为我使用的是 url(...) 并且需要解析 url。
现在我正在做:
Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>"));
但我希望有一些更优雅的东西?
我想这不是解决问题的坏方法。如果你有一个外部样式表文件,这段代码就可以完成工作:
HtmlLink cssRef = new HtmlLink();
cssRef.Href = "styles/main.css";
cssRef.Attributes["rel"] = "stylesheet";
cssRef.Attributes["type"] = "text/css";
Page.Header.Controls.Add(cssRef);
另一个想法是编写你自己的 ASP.NET ServerControl “HtmlInlineStyle”,所以你可以这样调用它(脚本标签将由你的服务器控件完成):
Page.Header.Controls.Add(
New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }");
此博客条目和评论显示了一些替代方案 (ScriptManager.RegisterClientScriptBlock)。但在我看来,你的解决方案是可以的。
这是另一种方式......例如:
父 ASPX 部分:
<div id="div1" class="xyz" style="width: 40px; height: 40px;">
<span>abc</span>
</div>
在控制范围内:
Dim xyzStyle As New Style()
xyzStyle.CssClass = "xyz"
xyzStyle.BackColor = Drawing.Color.LightBlue
Page.Header.StyleSheet.CreateStyleRule(xyzStyle, Nothing, ".xyz")
请注意,这假定父 ASPX 页面具有为目标控件设置的类属性。如果没有,那么您将需要使用 MergeStyle 方法将样式与控件合并。(这要求控制是runat="server"
)。
此代码呈现以下输出:(为方便起见,显示整个源代码)
<html>
<head>
<title>Untitled Page </title>
<style type="text/css">
.xyz { background-color:LightBlue; }
</style>
</head>
<body>
<form name="form1" method="post" action="MyPage.aspx" id="form1">
<div id="div1" class="xyz" style="width: 40px; height: 40px;">
<span>abc</span>
</div>
</form>
</body>
</html>
我创建自己的类并继承 Style,并使用我自己的字典来查找默认 Style 类不包含的属性。这是一个简短的例子......
protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver)
{
Dictionary<String, String> _styles = new Dictionary<string, string>();
_styles.Add("display", "inline-block");
foreach (String s in _styles.Keys)
{
attributes[s] = (String)_styles[s];
}
base.FillStyleAttributes(attributes, urlResolver);
}