1 添加自定义属性
将属性添加到用户控件中
在解决方案资源管理器中,右击“ctlClock.cs”,然后从快捷菜单中单击“查看代码”。
控件的代码编辑器打开。
找到 public class ctlClock 语句。在开始的 { 后面,键入:
private Color colFColor;
private Color colBColor;
这些语句会创建私有变量,用来存储要创建的属性的值。
在步骤 2 中的变量声明下方键入以下代码:
// Declares the name and type of the property.
public Color ClockBackColor
// Retrieves the value of the private variable colBColor.
{
get
{
return colBColor;
}
// Stores the selected value in the private variable colBColor, and
// updates the backcolor of the label control lblDisplay.
set
{
colBColor = value;
lblDisplay.BackColor = colBColor;
}
}
// Provides a similar set of instructions for the forecolor.
public Color ClockForeColor
{
get
{
return colFColor;
}
set
{
colFColor = value;
lblDisplay.ForeColor = colFColor;
}
}
前述的代码使两个自定义属性(ClockForeColor 和 ClockBackColor)可用于该控件后面的用户。Get 和 Set 语句提供属性值的存储和检索,以及提供实现适合于属性的功能的代码。
2 添加自定义事件
UserControl.ascx.cs中的处理:
1. 定义public的事件委托,如ClickEventHandler;
2. 在UserControl类中声明事件,如Click;
3. 在UserControl类中定义引发事件的方法,如OnClick()方法;
4. 在UserControl类的相关方法中调用引发事件的方法,如在Button_Click()中调用OnClick()。
public class WebUserControl1 : System.Web.UI.UserControl
{
public delegate void ppp(object sender, EventArgs e);
//事件显示为killBill
public event ppp killBill;
//通过label 的事件调用新事件,实现新增事件
private void lblDisplay_Click(object sender, EventArgs e)
{
if (killBill != null)
{
killBill(sender, e);
}
}
}
2.继承自Control类
3.继承自UserControl类
具有一些默认属性和事件
自定义属性和事件的显示通过上述方法