12

I'm looking to do something akin to

<cstm:MyControl runat="server">
    <myItem attr="something" />
    <myItem attr="something" />
</cstm:MyControl>

What's the bare bones code needed to pull this off?

Rick's example shows something akin to

<cstm:MyControl runat="server">
    <myItems>
        <cstm:myItem attr="something" />
        <cstm:myItem attr="something" />
    </myItems>
</cstm:MyControl>

I'd prefer the more terse syntax if possible.

Note: Feel free to suggest a better title or description. Even if you don't have edit rights, I'm glad to edit the entry for the sake of the community.

Larsenal
  • 49,878
  • 43
  • 152
  • 220
  • I would suggest changing the title of this to be "How do you build an ASP.NET custom control with a default collection property?", since there are a few explanations on building a control with a declarative collection property, but few explain how to make it the default property. – Chris Pietschmann Sep 23 '08 at 21:10

1 Answers1

17

Here's a really simple example control that does exactly what you are looking for:

namespace TestControl
{
    [ParseChildren(true, DefaultProperty = "Names")]
    public class MyControl : Control
    {
        public MyControl()
        {
            this.Names = new List<PersonName>();
        }

        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public List<PersonName> Names { get; set; }
    }

    public class PersonName
    {
        public string Name { get; set; }
    }
}

And, here is an example usage:

<%@ Register Namespace="TestControl" TagPrefix="TestControl"  %>

<TestControl:MyControl runat="server" ID="MyControl1">
    <TestControl:PersonName Name="Chris"></TestControl:PersonName>
    <TestControl:PersonName Name="John"></TestControl:PersonName>
</TestControl:MyControl>
nothingisnecessary
  • 6,099
  • 36
  • 60
Chris Pietschmann
  • 29,502
  • 35
  • 121
  • 166