如何将子节点添加到从System.Web.UI.Control派生的自定义asp.net用户控件

我想知道如何将一些额外的子节点添加到从System.Web.UI.Control派生的自定义用户控件类。

例如,目前我有一个不包含子节点的控件,在设计图面上如下所示。

 

我正在寻找的是能够从设计表面向该控件添加n个子节点,然后从代码中访问它们的值。 所以加入上述控制。

  value1 value2  

我不清楚如何访问子节点。

任何有关如何做到这一点的见解表示赞赏。

您希望能够以声明方式描述asp.net控件属性 。

能够拥有以下标记:

       

您需要以下代码:

 [ParseChildren(true)] [PersistChildren(true)] [ToolboxData("<{0}:CustomControlUno runat=server>")] public class CustomControlUno : WebControl, INamingContainer { private Control1ChildrenCollection _children; [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Control1ChildrenCollection Children { get { if (_children == null) _children = new Control1ChildrenCollection(); return _children; } } } public class Control1ChildrenCollection : List { } public class Control1Child { public int IntegerProperty { get; set; } private string StringProperty { get; set; } } 

如果您希望按原样支持给定的语法(无需使用标记前缀),则可以使用ControlBuilder:

  //MyControlBuilder public class MyControlBuilder : ControlBuilder { public override Type GetChildControlType(string tagName, IDictionary attribs) { if (tagName.StartsWith("childnode")) return typeof(Control); else return base.GetChildControlType(tagName,attribs); } public override void AppendLiteralString(string s) { //ignore literals betwen tags } } //MyCustomControl [ParseChildren(false)] [ControlBuilder(typeof(MyControlBuilder))] public class MyCustomControl : Control { public string attribute1 {get;set;} public string attribute2 {get;set;} protected override void AddParsedSubObject(object obj) { Control ctrl = (Control) obj; LiteralControl childNode = ctrl.Controls[0]; //Add as-is (eg, literal "value1") Controls.Add(childNode); } } 

另请参见http://msdn.microsoft.com/en-us/library/system.web.ui.controlbuilder.aspx