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

后端 未结 1 1133
春和景丽
春和景丽 2021-01-14 10:27

For example:



My Data



        
相关标签:
1条回答
  • 2021-01-14 10:46

    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 讨论(0)
提交回复
热议问题