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

Asked

Viewed 149 times

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 having to use a template explicitly.

Currently I have it:

<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 of 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 put the controls directly inside my control, without having to place the template? In the same way as the Panel works...

1 answer

2


It is not necessary to use the template, just add these attributes to your control:

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

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

Persistchildrenattribute.Persist sets whether tags within the control will be treated as sub-controls. 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 it will be possible to use:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.