开发者

How do you programmatically create a default template for a templated control?

开发者 https://www.devze.com 2023-01-01 04:27 出处:网络
I\'m creating a cus开发者_如何转开发tom templated composite control. If there is no \'ItemTemplate\' specified in the mark-up, how do I create a default template programmatically?Right, maybe I should

I'm creating a cus开发者_如何转开发tom templated composite control. If there is no 'ItemTemplate' specified in the mark-up, how do I create a default template programmatically?


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

0

精彩评论

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