I want to create a control just like a Panel.
I want my control to accept some controls as childs without typing the template name, just like the Panel, as shown here:
<asp:Panel runat="server">
My content
<div>Content</div>
</asp:Panel>
I have controls with content inside without telling what is the ITemplate.
I basically want to convert this
<my:MyControl runat="server">
<ContentTemplate>
My content
<div>Content</div>
</ContentTemplate>
</my:MyControl>
Into this
<my:MyControl runat="server">
My content
<div>Content</div>
</my:MyControl>
Here is what I’ve got:
public class MyControl : CompositeControl
{
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content { get; set; }
protected override void CreateChildControls()
{
base.CreateChildControls();
Content.InstantiateIn(this);
}
}
The above works with <Content></Content> tags inside the control, but without it doesn’t work. And the attribute isn’t doing anything at all (I guess). What’s missing?
How can I achieve it? Any hints? Why does Panel support this?
I’m writting this from memory but I believe the answer is a simple as decorating your control class with the attributes ParseChildrenAttribute and PersistChildrenAttribute and you do not need to work with templates as you are proposing.
ParseChildrenAttribute.ChildrenAsProperties specifies whether the parser should treat the nested content of the control tag as properties. Setting this to false will make the parser not to try to map the tags to property names.
The PersistChildrenAttribute will tell the parser to treat the nested content as controls and the parsed controls will be added as child controls to your custom panel control.
The code for your control would then look something like this:
For reference you could fire up .NET Reflector and look at the implementation of the Panel control.