If I understood correctly, you define controls in the template and expect to use them in a custom control the way they are used in a user control.
If so, let me explain to you. The ASP.NET runtime automatically maps variables
with the same name as control ids to the controls in the .ascx file. Visual studio does the rest of the magic with its intellisense. This is the reason why user controls are partial
classes. This is when you are dealing with user controls.
When you are doing custom controls
, you don't need a template at all. It is optional, but it is a good practice, as well. The custom control's template is not
a user control. It is just some markup that separates business logic from the UI layout. In a custom control, if you are using templates, it is your responsibility to load the template and then map the controls in the template to variables/properties.
How to map a control in a template to a property?
Since you should use the new backend architecture, you will ultimately derive from SimpleControl or ViewModeControl<THost>. They both implement a Container property, of type GenericContainer. GenericContainer has this method:
|public virtual T GetControl<T>(string id, bool required)
which actually is just one of the four methods with the same name. The generic argument is the type of the control you want to search for; e.g. if you have
|<asp:Label id="firstName" runat="server" />
, you would search for System.Web.UI.WebControls.Label, like so:
|Label firstName = this.Container.GetControl<Label>("firstName", false);
The paramerers mean:
- string id
Id of the control in the template
- bool required
Whether to throw an exception if the control is not found (true), or return null (false)
As you can see, this is very similar to System.Web.UI.Control's FindControl(string id) method, which is used often in custom data binding.
As a conversion, here at Sitefinity, we define a public property for every server control in the template. If we follow the previous example, our property would look like:
|public ITextControl FirstName
| return this.Container.GetControl<ITextControl>("firstName", false);
Here I use ITextControl, because Label implements this interface, but so does Literal. This gives me the flexibility to change the control type in the template without changing my business logic.
I hope will find this information useful.
the Telerik team
, the state of the art learning tool for Telerik products.