views:

26

answers:

1

I'm creating a custom templated composite control. If there is no 'ItemTemplate' specified in the mark-up, how do I create a default template programmatically?

A: 

Right, maybe I should have played around with it a bit before posting my question. I've created the following class:

internal class ItemTemplateDefault : ITemplate
{
    public void InstantiateIn(Control container)
    {
        Literal lit = new Literal();

        CountrySelectorItemContainer cont = container as CountrySelectorItemContainer;

        lit.Text = string.Format("<li>\n\t<a href=\"{0}\" title=\"{1}\">{1}</a>\n</li>", cont.ItemURL, cont.ItemText);

        container.Controls.Add(lit);
    }
}

So when if the ItemTemplate is null, I instantiate a new ItemTemplateDefault and assign it as ItemTemplate. See below.

if (this.ItemTemplate == null)
    this.ItemTemplate = new ItemTemplateDefault();

CountrySelectorItemContainer container = new CountrySelectorItemContainer();
container.ItemText = "My Country";
container.ItemURL = "http://myurl.com";

this.ItemTemplate.InstantiateIn(container);

Controls.Add(container);

Is this a decent way of doing this? I really just thought up what seemed natural, so I would appreciate it if you have any feedback.

Cheers, James

No Average Geek