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

时间:2010-09-04 14:50:54

标签: c# .net asp.net user-controls

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

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

<cust:MyCustomControl id="ctlMyCustomControl" runat="server" attribute1="somevalue" attribute2="somevalue" ></MyCustomControl>

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

<cust:MyCustomControl id="ctlMyCustomControl" runat="server" attribute1="somevalue" attribute2="somevalue" >
  <childnode1>value1</childnode1>
  <childnode2>value2</childnode2>
</MyCustomControl>

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

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

2 个答案:

答案 0 :(得分:6)

您希望能够describe asp.net control properties declaratively

能够拥有以下标记:

<Abc:CustomControlUno runat="server" ID="Control1">
    <Children>
        <Abc:Control1Child IntegerProperty="1" StringProperty="Item1" />
        <Abc:Control1Child IntegerProperty="2" StringProperty="Item2" />
    </Children>
</Abc:CustomControlUno>

您需要以下代码:

[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; }
}

答案 1 :(得分:4)

如果您希望按原样支持给定语法(无需使用标记前缀),则可以使用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 (e.g., literal "value1")
     Controls.Add(childNode);
   }
 }

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