ASP.NET 2.0在控件中动态添加页面样式

6
我需要在自定义控件中向页面添加

。我不能使用样式表(.css),因为我使用了url(...)并需要解析url。

目前我正在做:

Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>"));

但我希望有些更优雅的东西?
3个回答

3
我猜这不是一个坏的解决方案。如果你有一个外部样式表文件,这段代码可以起到作用:
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 服务器控件 "HtmlInlineStyle",这样您就可以这样调用它(脚本标记将由您的服务器控件完成):
Page.Header.Controls.Add(
   New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }");

这篇博客文章和评论提供了一些替代方案(ScriptManager.RegisterClientScriptBlock)。但是在我看来,你的解决方案还可以。

什么是HtmlInlineStyle?我找不到这个类。 - Anton Putov
@AntonPutov 在.NET框架中没有这样的类。这只是建议您编写自己的服务器控件。 - splattne

1
这里有另外一种方法...例如:
父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 方法将样式与控件合并。 (这需要控件运行在服务器上)。
此代码呈现以下输出:(为方便起见显示整个源)
<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>

1
是的...我找到了CreateStyleRule,但很烦恼的是它没有提供一种方法来提供额外的“styles”字符串设置。我需要的样式属性大多不是Style()对象的一部分。 - user53794
嗯...非常正确。我还没有找到解决那个问题的方法。 - Cerebrus

0
我创建了自己的类并继承了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);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接