I am going to demonstrate the basics of setting templates programmatically. To do a basic demonstration, I will use the simple template example that was demonstrated at the beginning of the article. But first, let’s create the template class:
public class SimpleCustomTemplate : ITemplate {
public void InstantiateIn(Control container) {
container.Controls.Add(new LiteralControl(“Hello World from the template”));
}
}
Is it simple? To do a follow through, the InstantiateIn method is called. It then adds a literal control to the container control which is parsed by the only parameter. Now to hook it up with the control provided earlier in the article:
public class ExtendedTemplateControl : SimpleTemplateControl {
public ExtendedTemplateControl() {
SimpleTemplate = new SimpleCustomTemplate();
}
}
The code is really simple: all it does is set the SimpleTemplate property to the template that was defined earlier on this page (the SimpleCustomTemplate class). This, however, allows the page developer to override our template by the usual course. If you want to force your custom template, then do it at the last minute – at the CreateChildControls method:
public class ExtendedForcedTemplateControl : SimpleTemplateControl {
public overrides void CreateChildControls() {
SimpleTemplate = new SimpleCustomTemplate();
base.CreateChildControls();
}
}