ASP.NET用戶控件返回事件的方法
2024-07-10 12:57:29
供稿:網友
 
asp.net用戶控件一般適用于產生相對靜態的內容,所以沒有builtin的事件支持。本文討論用戶控件返回事件的方法。
 假定用戶控件(usercontrol.ascx)中包含按鈕控件abutton,希望實現按abutton按鈕時,包含該用戶控件的頁面可以接收到事件。為此,小雞射手在用戶控件和頁面的代碼中分別作了處理。
 usercontrol.ascx.cs中的處理:
 1. 定義public的事件委托,如clickeventhandler;
 2. 在usercontrol類中聲明事件,如click;
 3. 在usercontrol類中定義引發事件的方法,如onclick()方法;
 4. 在usercontrol類的相關方法中調用引發事件的方法,如在button_click()中調用onclick()。
 核心代碼示意如下:
 public delegate void clickeventhandler(object sender, eventargs e);
 public class myusercontrol : system.web.ui.usercontrol
 {
 protected system.web.ui.webcontrols.button abutton;
 public event clickeventhandler click;
 protected void onclick(eventargs e) 
 {
 if (click!=null) click(this, e); 
 }
 private void abutton_click(object sender, system.eventargs e)
 {
 this.onclick(e);
 }
 }
 包含usercontrol的頁面cs文件中的處理:
 1. initializecomponent()中增加事件處理程序,采用findcontrol方法找到usercontrol;
 2. 定義事件處理方法,在該方法中處理usercontrol的事件,如usercontrol_clicked()。
 核心代碼示意如下:
 private void initializecomponent()
 { 
 this.load += new system.eventhandler(this.page_load);
 myusercontrol uc = this.findcontrol("myusercontrolid") as myusercontrol;
 uc.click += new clickeventhandler(this.usercontrol_clicked);
 }
 private void usercontrol_clicked(object sender, system.eventargs e)
 {
 // usercontrol_clicked event hanlder
 }
 總結一下,其實就是將事件機制利用手工編程的方法加進去:加入一般控件ide自動生成的代碼。順便說一下,c#的事件機制實現了obeserver pattern,除了ui還可以用于業務層,能有效地降低對象間的耦合度,像usercontrol那樣,根本無需知道包含它的頁面對象是誰!