ASP.NET自定义控件 - 允许文字内容的模板
问题描述:
我希望我的用户控件能够在其中包含文字内容。例如:ASP.NET自定义控件 - 允许文字内容的模板
<fc:Text runat="server">Please enter your login information:</fc:Text>
目前为我的用户控件的代码是:
<ParseChildren(True, "Content")> _
Partial Public Class ctrFormText
Inherits UserControl
Private _content As ArrayList
<PersistenceMode(PersistenceMode.InnerDefaultProperty), _
DesignerSerializationVisibility(DesignerSerializationVisibility.Content), _
TemplateInstance(TemplateInstance.Single)> _
Public Property Content() As ArrayList
Get
If _content Is Nothing Then
Return New ArrayList
End If
Return _content
End Get
Set(ByVal value As ArrayList)
_content = value
End Set
End Property
Protected Overrides Sub CreateChildControls()
If _content IsNot Nothing Then
ctrChildren.Controls.Clear()
For Each i As Control In _content
ctrChildren.Controls.Add(i)
Next
End If
MyBase.CreateChildControls()
End Sub
End Class
当我把文本此控件(如上面)我得到这个错误:
Parser Error Message: Literal content ('Please enter your login information to access CKMS:') is not allowed within a 'System.Collections.ArrayList'.
此控件可能包含其他内容而不仅仅是文本,因此将Content属性设置为属性不会解决我的问题。
我发现在一些地方,我需要实现一个ControlBuilder类,以及另一个类实现IParserAccessor。
无论如何,我只是希望我的默认“内容”属性具有允许在其中的所有类型的控件,包括文字和实际控件。
答
您需要将ParseChildren
属性设置为“False”,否则控件中的任何内容都将被解析为“Content”属性。这不符合您的需求,因为您想拥有控件和内容。
为了做到这一点,请覆盖AddParsedSubObject方法。检查解析的控件类型,如果它是文字控件,请将其添加到您的UserControl的Content
属性中。如果是其他控件,只需像往常一样将它添加到Controls
集合。
解析所有子对象后,只需在文字控件或面板中显示Content
属性即可。