|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
How to: Create Templated ASP.NET User Controls
You can create user controls that implement templates, an ASP.NET feature that allows the separation of control data from its presentation. A templated control does not provide a user interface. Instead, it is written to implement a naming container and to include a class whose properties and methods are accessible to the host page.
The user interface for the user control is supplied by a page developer at design time. The developer creates templates of the type defined by the user control, and can then add controls and markup to the templates.
To create a templated user control
In the .ascx file, add an ASP.NETcontrol where you want the template to appear.
In the user control's code, implement a property of type.
Define a server control class that implements theinterface as a container in which to create an instance of the template. This is called the template's naming container.
This control essentially becomes a nested class of the user control, though this is not required.
Apply theto the property that implements ITemplate and pass the type of the template's naming container as the argument to the attribute's constructor.
In the control'smethod, repeat the following steps one or more times:
Create an instance of the naming container class.
Create an instance of the template in the naming container.
Add the naming container instance to theproperty of the PlaceHolder server control.
From the point of view of the page using the user control, the syntax for the templated user control is identical to what it would be with a custom templated control.
The following example shows a templated user control and a page that contains it. The user control creates a template that can be declared on a host page as
<MessageTemplate>. The template control also exposes two properties,
Message, that the host page can access inside the template.
The first sample shows the templated user control. The second sample shows a page that contains the user control.