用户控件添加自定义事件
给用户控件添加自定义事件需要一下几个步骤:
1.定义委托
2.声明事件
3.定义事件触发函数
4.注册事件
定义委托:
public delegate void LogInOutClickHandler(object sender,LogInOutEventArgs e);
其中LogInOutEventArgs类是从EventArgs类继承(把这个delegate放在LogInOutControl类外面更为合适)。
如果使用系统的EventHandler委托,也可以不定义委托。
不使用EventHandler开发时,需要自定义EventArgs类,如下:
public class LogInOutEventArgs : EventArgs
{
private LogInClickType type;
private bool result;
public LogInOutEventArgs(LogInClickType type,bool result):base()
{
this.type = type;
this.result = result;
}
public LogInClickType Type
{
get{return this.type;}
}
public bool Result//操作结果
{
get{return this.result;}
}
}
public enum LogInClickType : int //操作类型
{
LongIn,
LongOut
}
}
声明事件:
public event LogInOutClickHandler LogInOutClick;
定义事件触发函数:
定义控件事件触发函数OnLogInOutClick,由按钮单击事件处理函数来完成对用户控件事件的触发。
private void ButtonLogIn_Click(object sender, System.EventArgs e)
{//使用按钮提交事件,并触发用户控件的事件
OnLogInOutClick(this,new LogInOutEventArgs(LogInClickType.LongIn,CustomValidate(this.TextBoxUserName.Text,this.TextBoxPassword.Text)));
}
private void OnLogInOutClick(object sender,LogInOutEventArgs e)
{//处理参数函数,LogInOutEventArgs,并提交事件(向上一级页面提交)
if(LogInOutClick!=null)
LogInOutClick(this,e);
}
注册事件:
private void InitializeComponent()
{
this.LogInOutControl1.LogInOutClick += new LogInOutClickHandler(LogInOutControl1_LogInOutClick);
}
参考:http://www.knowsky.com/4204.html