ASP.NET 2.0动态地向控件中的页面添加样式

时间:2009-02-25 07:47:54

标签: asp.net custom-server-controls

我需要从自定义控件中添加到页面。我不能使用样式表(.css),因为我正在使用url(...)并需要解析url。

现在我正在做:

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

但我希望触摸更优雅的东西?

3 个答案:

答案 0 :(得分: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 ServerControl “HtmlInlineStyle”,这样您就可以这样调用它(脚本标记将由您的服务器控件完成):

Page.Header.Controls.Add(
   New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }");

这个blog entry和评论显示了一些替代方案(ScriptManager.RegisterClientScriptBlock)。但在我看来,你的解决方案还可以。

答案 1 :(得分: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方法样式与控件合并。 (这要求控件为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>

答案 2 :(得分: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);
    }
相关问题