开发者

ASP.NET custom control, can template fields have attributes?

开发者 https://www.devze.com 2023-02-14 08:48 出处:网络
For example: <uc:AdmiralAckbar runat=\"server\" id=\"myCustomControl\"> <Warning SomeAttribute=\"It\'s A Trap\">

For example:

<uc:AdmiralAckbar runat="server" id="myCustomControl">
<Warning SomeAttribute="It's A Trap">
My Data
</Warning>
</uc:AdmiralAckbar>

I'm not sure how to add SomeAttribute. Any ideas?

Code without the attribute is:

private ITemplate warning = null;

    [开发者_开发问答TemplateContainer(typeof(INamingContainer))]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate Warning
    {
        get
        {
            return warning;
        }
        set
        {
            warning = value;
        }
    }


The answer is yes.

For this you should create a type which implements ITemplate interface and add a custom property/properties there (I added property Name in my example); also add a class which inherits from Collection<YourTemplate>.

Here is an example of doing that:

public class TemplateList : Collection<TemplateItem> { }

public class TemplateItem : ITemplate
{
    public string Name { get; set; }

    public void InstantiateIn(Control container)
    {
        var div = new HtmlGenericControl("div");
        div.InnerText = this.Name;

        container.Controls.Add(div);
    }
}

and a control itself:

[ParseChildren(true, "Templates"), PersistChildren(false)]
public class TemplateLibrary : Control
{
    public TemplateLibrary()
    {
        Templates = new TemplateList();
    }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public TemplateList Templates { get; set; }

    protected override void RenderChildren(HtmlTextWriter writer)
    {
        foreach (var item in Templates)
        {
            item.InstantiateIn(this);
        }

        base.RenderChildren(writer);
    }
}

and finally an example of usage:

<my:TemplateLibrary runat="server">
    <my:TemplateItem Name="hello" />
    <my:TemplateItem Name="there" />
</my:TemplateLibrary>

BTW, you could also use it as:

<my:TemplateLibrary runat="server">
    <Templates>
        <my:TemplateItem Name="hello" />
        <my:TemplateItem Name="there" />
    </Templates>
</my:TemplateLibrary>

the effect will be the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消