How can I create a control that has subcontractors without explicitly adding a template?

0

I want to create a control exactly like a Panel .

<asp:Panel runat="server">
    Conteúdo
    <div>Content</div>
</asp:Panel>

I want to be able to put controls inside it without explicitly using a template.

I currently have this:

<my:MyControl runat="server">
    <ContentTemplate>
        Conteúdo
        <div>Conteúdo</div>
    </ContentTemplate>
</my:MyControl>

I want to convert to:

<my:MyControl runat="server">
    Conteúdo
    <div>Conteúdo</div>
</my:MyControl>

The current code for my control is:

public class MyControl : CompositeControl
{
    [TemplateInstance(TemplateInstance.Single)]
    public ITemplate Content { get; set; }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        Content.InstantiateIn(this);
    }
}

How can I make the controls directly inside my control, without having to put the template? Just as Panel works ...

    
asked by anonymous 20.12.2013 / 06:17

1 answer

2

You do not need to use the template, just add these attributes to your control:

[ParseChildren(false)]
[PersistChildren(true)]

ParseChildrenAttribute.ChildrenAsProperties defines whether the tags inside the control will be treated as control properties. In this case false indicates that they will not be considered as properties.

PersistChildrenAttribute.Persist defines whether tags within the will be treated as subcontractors. In this case true indicates that controls will be considered.

So just declare your control as:

[ParseChildren(false)]
[PersistChildren(true)]
public class MyControl : CompositeControl 
{
} 

And you can use:

<my:MyControl runat="server">
    Conteúdo
    <div>Conteúdo</div>
</my:MyControl>
    
20.12.2013 / 06:17