範本控件開發比組合控件更簡單,核心在於繼承 CompositeControl 並定義 ITemplate 屬性。本章將改造上章的登入控件,讓使用者能自訂輸入欄位的控件類型(TextBox、DropDownList 等)。
定義 LoginTemplate、PasswordTemplate 等屬性,並在 CreateChildControls 中實例化:
[TemplateContainer(typeof(LoginContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate LoginTemplate { get; set; }

使用時只需在標記中嵌入自訂內容:
<cc:TemplatedLogin runat="server">
<LoginTemplate>
<asp:DropDownList ID="UserList" runat="server" />
</LoginTemplate>
<PasswordTemplate>
<asp:TextBox TextMode="Password" runat="server" />
</PasswordTemplate>
</cc:TemplatedLogin>
範本控件賦予使用者極大彈性,是構建可重用 UI 元件的利器。