日期:2008-09-26 浏览次数:20488 次
如果在C#中实现用户定义控件内的事件挂勾到调用的窗体事件中
细节如下:1、新建应用程序WindowsApplication1。2、添加新的用户控件UserLogin。(如图User)3、定义用户属性//定义属性
public string Username
{
get{return username;}
set{username=value;}
}
public string Password
{
get{return password;}
set{password=value;}
}
//定义委托
public delegate void btnOkClickEventHander(object sender,EventArgs e);
public delegate void btnCancelClickEventHander(object sender,EventArgs e);
//定义事件
public event btnOkClickEventHander btnOkClick;
public event btnCancelClickEventHander btnCancelClick6、事件实现private void textBoxUid_TextChanged(object sender, System.EventArgs e)
{
Username=this.textBoxUid.Text;
}private void textBoxPwd_TextChanged(object sender, System.EventArgs e)
{
Password=this.textBoxPwd.Text;
}private void buttonOK_Click(object sender, System.EventArgs e)
{
if (btnOkClick!=null)
btnOkClick(this,e);
}private void buttonCancel_Click(object sender, System.EventArgs e)
{
if (btnCancelClick!=null)
btnCancelClick(this,e);
}7、在FORM1的WinForm中实现对用户控件事件的调用,消息的接收。protected void okClick(object send,System.EventArgs e)
{
MessageBox.Show("UID:"+userLogin1.Username+";PWD:"+userLogin1.Password,"UserMessage");
}protected void CancelClick(object send,System.EventArgs e)
{
this.Close();
}8.按F5运行(如图Result)附1(WindowsApplication1源代码)using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;namespace WindowsApplication1
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
private WindowsApplication1.UserLogin userLogin1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
userLogin1.btnOkClick+=new btnOkClickEventHander(okClick);
userLogin1.btnCancelClick+=new btnCancelClickEventHander(CancelClick);