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

For instance:

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

I am not sure how to add SomeAttribute. Any ideas?

Code without attribute:

private ITemplate warning = null;

    [TemplateContainer(typeof(INamingContainer))]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate Warning
    {
        get
        {
            return warning;
        }
        set
        {
            warning = value;
        }
    }
+3
source share
1 answer

The answer is yes.

To do this, you must create a type that implements the interface ITemplateand adds custom property / properties to it (I added the property Namein my example); also add a class that inherits from Collection<YourTemplate>.

Here is an example of this:

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 the 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 a usage example:

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

By the way, you can 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.

+4
source

Source: https://habr.com/ru/post/1796007/


All Articles