zwei1121

博客园 首页 新随笔 联系 订阅 管理
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那样,根本无需知道包含它的页面对象是谁!

posted on 2007-12-21 18:32  zwei  阅读(231)  评论(0编辑  收藏  举报