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

。_饼干妹妹 提交于 2019-12-01 05:40:35

问题


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;
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/5179599/asp-net-custom-control-can-template-fields-have-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!