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

Dou*_*oug 6 .net c# asp.net user-controls

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

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

<cust:MyCustomControl id="ctlMyCustomControl" runat="server" attribute1="somevalue" attribute2="somevalue" ></MyCustomControl>
Run Code Online (Sandbox Code Playgroud)

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

<cust:MyCustomControl id="ctlMyCustomControl" runat="server" attribute1="somevalue" attribute2="somevalue" >
  <childnode1>value1</childnode1>
  <childnode2>value2</childnode2>
</MyCustomControl>
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*Rob 6

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

能够拥有以下标记:

<Abc:CustomControlUno runat="server" ID="Control1">
    <Children>
        <Abc:Control1Child IntegerProperty="1" StringProperty="Item1" />
        <Abc:Control1Child IntegerProperty="2" StringProperty="Item2" />
    </Children>
</Abc:CustomControlUno>
Run Code Online (Sandbox Code Playgroud)

您需要以下代码:

[ParseChildren(true)]
[PersistChildren(true)]
[ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]
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<Control1Child>
{
}

public class Control1Child
{

    public int IntegerProperty { get; set; }
    private string StringProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)