简体   繁体   English

您如何以编程方式为模板控件创建默认模板?

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

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? 如果在标记中未指定“ ItemTemplate”,如何以编程方式创建默认模板?

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. 如果ItemTemplate中是空所以,当我实例化一个新ItemTemplateDefault并将其指定为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 干杯,詹姆斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从XAML中定义的数据模板以编程方式创建元素? - How do you create an element programmatically from a data template defined in XAML? 如何将复杂对象手动数据绑定到模板化控件(如gridview中的行)? - How do you manually databind complex object to templated control like a row in a gridview? 如何正确地做一个模板类的模板? - How to properly do a template of a templated class? 如何以编程方式调整 PropertyGrid 控件的水平分隔线? - How do you programmatically adjust the horizontal divider of a PropertyGrid control? 如何在按钮的控件模板中将TemplateBindings更改为Bindings,而不重复整个控件模板 - How do you change TemplateBindings to Bindings in a button's control template, without repeating the whole control template 如何以编程方式在C#中创建MS Access表? - How do you create an MS Access table in C# programmatically? 如何以编程方式创建LongListSelector控件 - How to create a LongListSelector control programmatically 具有两个模板的模板化用户控件,如何在其他模板中查找需要控件ID的属性的控件 - Templated User Control with two templates how to find control in other template for properties which require control id 如何以编程方式在gridview模板中添加控件? - How add control programmatically in gridview template? 控件模板:如何创建绑定 - Control template: how to create bindings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM