Minimal implementation of a custom templated ASP.NET control using the ITemplate interface
Below you will find a code snippet to demonstrate a minimal implementation of a custom ASP.NET control that allows page designers to specify a template which will be used by the control to render itself, using the ITemplate interface.
Markup:
1: <my:MyTemplateBasedControl runat="server" id="myTemplateBasedControl1">
2: <MyHeaderTemplate>
3: <div>
4: Some text <asp:Button runat="server" Text="And a button..." />
5: </div>
6: </MyHeaderTemplate>
7: </my:MyTemplateBasedControl>
Control code:
1: public class MyTemplateBasedControl : CompositeControl
2: {
3: public ITemplate MyHeaderTemplate { get; set; }
4:
5: public MyTemplateBasedControl()
6: {
7:
8: }
9:
10: protected override void CreateChildControls()
11: {
12: base.CreateChildControls();
13:
14: // If <MyHeaderTemplate></MyHeaderTemplate> was supplied
15: // in the page that contains this control, then this.HeaderTemplate
16: // will automatically be set for you with an object of type
17: // System.Web.UI.CompiledTemplateBuilder
18: if (this.MyHeaderTemplate != null)
19: {
20: // let's instantiate multiple instances of our template
21: for (int i = 0; i < 10; i++)
22: {
23: // This will "convert" the string supplied inside
24: // <MyHeaderTemplate></MyHeaderTemplate> into 0 or more controls.
25: // Each of these controls will be added to this.Controls
26: // since we pass in "this" into the InstantiateIn() method
27: this.MyHeaderTemplate.InstantiateIn(this);
28: }
29: }
30: }
31: }
Result:
[…] This post was mentioned on Twitter by Jaap Vossers. Jaap Vossers said: Minimal implementation of a custom templated ASP.NET control using the ITemplate interface http://bit.ly/a3t874 #csharp #aspnet […]
Tweets that mention Minimal implementation of a custom templated ASP.NET control using the ITemplate interface « Jaap Vossers’ SharePoint Blog -- Topsy.com
May 13, 2010 at 6:56 pm