Jaap Vossers' SharePoint Blog

Just another WordPress.com site

Minimal implementation of a custom templated ASP.NET control using the ITemplate interface

with one comment

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:

itemplate_result

Written by jvossers

May 12, 2010 at 3:35 pm

Posted in ASP.NET, Development

One Response

Subscribe to comments with RSS.

  1. […] 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 […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: