如何更改自定义控件的呈现行为,使其不再是跨度
编写自定义控件时,它始终呈现为 HTML span 元素。 例如,我如何将其更改为 div?
When writing a custom control it always rendered as an HTML span element.
How can I change it for example to a div?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
按如下方式从 WebControl 派生控件:
即,使用接受要使用的标记的基类构造函数。
Derive your control from WebControl as follows:
That is, use the base class constructor that accepts the tag to use.
如果从 CompositeControl 派生,则没有采用标记类型的构造函数。 您可以重写 TagKey (我没有尝试过),但更灵活的选择是重写 RenderBeginTag 方法并使其执行您想要的操作。 基类呈现一个“span”开始元素,但您不必调用基类方法。 如果您不想渲染任何内容,则不必调用任何内容(在这种情况下也覆盖 RenderEndTag 并且也不在那里调用任何内容)。 例如,
这段代码生成的
正是我的这个特定复合控件所需要的,一个带有类来包装 ReportViewer 控件的 div。 我添加 ID 只是为了使输出更易于识别。
If you derive from CompositeControl there is no constructor that takes a tag type. You can override TagKey (I haven't tried it), but a more flexible option is to override the RenderBeginTag method and make it do what you want. The base class renders a "span" opening element, but you don't have to call the base class method. You don't have to call anything if you don't want anything rendered (in which case also override RenderEndTag and don't call anything there either). For example,
This code produces
which is exactly what I needed for this particular composite control of mine, a div with a class to wrap a ReportViewer control. I include the ID just to make the output easier to spot.
我通常有自己的基类,所有复合控件都继承自该基类。 我添加到其中的属性之一是 ContainerElement。 公开暴露后,开发人员可以选择他们想要的外部元素。 它在内部设置了 TagKey 属性,该属性控制基本控件上的呈现。 以下所有内容均属于您的控件/基类。
您只需要设置 HTMLContainerElement 即可获得 HtmlTextWriterTag 枚举中所有项目的智能帮助。
I normally have my own base class that all my composite controls inherit from. One of the properties I add to this is a ContainerElement. Publicly exposed, the developer can choose what ever outer element they want. Internally it sets the TagKey property which governs this rendering on the base control. All the following to your control/base class.
You just need to set HTMLContainerElement which will have the inteli-help of all the items in the HtmlTextWriterTag enumeration.
此更改呈现包装 div 而不是 span
This change render the wrapping div instead of span