代码之家  ›  专栏  ›  技术社区  ›  Doug

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

  •  6
  • Doug  · 技术社区  · 14 年前

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

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

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

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

    2 回复  |  直到 14 年前
        1
  •  6
  •   Rob    14 年前

    你希望能够 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; }
    }
    
        2
  •  4
  •   Mark Cidade    14 年前

    如果希望支持给定的语法(不必使用标记前缀),可以使用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