基于我运行的简单测试,我认为不可能将内联<style>标记放入ASP.NET服务器控件中.该样式最终没有呈现给输出HTML.即使有可能,我也相信这样做是不好的做法.
是否有可能做到这一点?我可以看到它对于只有1或2个CSS类应用的快速原型很有用.
更新:
按照Jonathan的要求,我打算发布代码.但是,当我打开我的项目并再次加载页面时(只是为了踢)它正确运行.我的猜测是,它与重启Visual Studio在运行页面时启动的ASP.NET开发服务器有关.
无论如何,当我在页面上包含相同的多个控件时,我也得到了多个相同的样式.这可能是解释为什么这样做是件坏事.无论如何,了解完成任务的最佳实践和替代方法总是好的,所以我非常感谢大家的答案.
Nak*_*nch 47
Intellisense不会给你提示,但你可以这样做:
<asp:Label ID="Label1" runat="server" Text="Label" style="color:Red;"></asp:Label>
Run Code Online (Sandbox Code Playgroud)
Tom*_*son 13
样式元素位于头部.如果要在页面中包含样式表,则应在外部定义样式表,并使用它链接到该样式表
<link>.
因此,<style type="text\css"></style>在控件中包含样式元素(例如块)并不是一个好主意.如果可以的话,它可能会在某些浏览器中产生影响,但它不会验证并且是不好的做法.
如果要将样式内联应用于元素,则其中任何一个都可以工作:
C#
myControl.Attributes["style"] = "color:red";
myControl.Attributes.Add("style", "color:red");
Run Code Online (Sandbox Code Playgroud)
VB.NET
myControl.Attributes("style") = "color:red";
myControl.Attributes.Add("style", "color:red");
Run Code Online (Sandbox Code Playgroud)
但请记住,这将替换在style属性上设置的任何现有样式.如果您尝试在代码中的多个位置设置样式,这可能是一个问题,因此需要注意.
使用CSS类会更好,因为您可以对多个样式声明进行分组并避免冗余和页面膨胀.从WebControl派生的所有控件都有一个可以使用的CssClass属性,但请注意不要覆盖已在其他地方应用的现有类.
如果使用Attributes ["style"],则每次调用时都会覆盖该样式.如果您在两个不同的代码段中进行调用,则可能会出现问题.同样,它可能是一个问题,因为框架包括基本设置的属性,如边框和颜色,也将作为内联样式应用.这是一个例子:
// wrong: first style will be overwritten
myControl.Attributes["style"] = "text-align:center";
// in some other section of code
myControl.Attributes["style"] = "width:100%";
Run Code Online (Sandbox Code Playgroud)
为了好好玩,请设置这样的样式:
// correct: both style settings are applied
myControl.Attributes.CssStyle.Add("text-align", "center");
// in some other section of code
myControl.Attributes.CssStyle.Add("width", "100%");
Run Code Online (Sandbox Code Playgroud)