完成基本复合控件基本呈现
(1)首先你要熟悉以下的属性和方法
Control.CreateChildControls 方法用于创建子控件
Control.EnsureChildControls 方法用于确认是否已创建子控件,如果未创建完成的话则调用CreateChildControls 方法创建子控件
Control.ChildControlsCreated 属性 获取一个值,是否已创建子控件
(2)了解并实现INamingContainer接口
用户控件UserControl类则继承了INamingContainer接口,确包保子控件具有唯一的ID名称,那复合控件也需要实现这个接口达到一样的目的,这个是值得注意的地方.复合控件以类撰写的方法来添加控件即CreateChildControls 方法
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
namespace ComponentControl
{
public class Ctrl9:WebControl,INamingContainer
{
private Label m_NameLabel = new Label();
private Label m_PwdLabel = new Label();
private TextBox m_NameTextBox = new TextBox();
private TextBox m_PwdTextBox = new TextBox();
private Button m_Button = new Button();
private RequiredFieldValidator m_NameValidator = new RequiredFieldValidator();
private RequiredFieldValidator m_PwdValidator = new RequiredFieldValidator();
/// <summary>
/// 重写Controls的get属性,保证在访问复合控件的子控件时子控件已经被创建
/// EnsureChildControls()方法检查子控件是否被创建,如果没有被创建,
/// 将自动调用CreateChildControls()方法来创建子控件
/// </summary>
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
CreateChildControls
Properties
Render
}
}
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
namespace ComponentControl
{
public class Ctrl9:WebControl,INamingContainer
{
private Label m_NameLabel = new Label();
private Label m_PwdLabel = new Label();
private TextBox m_NameTextBox = new TextBox();
private TextBox m_PwdTextBox = new TextBox();
private Button m_Button = new Button();
private RequiredFieldValidator m_NameValidator = new RequiredFieldValidator();
private RequiredFieldValidator m_PwdValidator = new RequiredFieldValidator();
/// <summary>
/// 重写Controls的get属性,保证在访问复合控件的子控件时子控件已经被创建
/// EnsureChildControls()方法检查子控件是否被创建,如果没有被创建,
/// 将自动调用CreateChildControls()方法来创建子控件
/// </summary>
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
CreateChildControls
Properties
Render
}
}