首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 自訂控件開發 第四章(下):組合控件事件冒泡機制

     編輯:關於ASP.NET

組合控件 Login 由現有伺服器控件組成,子控件事件需「冒泡」為父控件事件。例如點擊「提交」按鈕,實際觸發 Login 的驗證事件。

事件冒泡實作步驟

  1. 定義事件資料類別:攜帶使用者名稱與密碼
  2. 在子控件事件處理器中引發父控件事件
  3. 對外公開父控件事件
public class ValidateEventArgs : EventArgs
{
    public string UserName { get; private set; }
    public string UserPassword { get; private set; }

    public ValidateEventArgs(string username, string userpassword)
    {
        UserName = username;
        UserPassword = userpassword;
    }
}

在 Button.Click 事件中:

protected void SubmitButton_Click(object sender, EventArgs e)
{
    string userName = UserNameTextBox.Text;
    string password = PasswordTextBox.Text;
    OnValidate(new ValidateEventArgs(userName, password));
}

protected virtual void OnValidate(ValidateEventArgs e)
{
    EventHandler<ValidateEventArgs> handler = Validate;
    if (handler != null) handler(this, e);
}

頁面使用者只需訂閱 Login.Validate 事件,無需知悉內部結構。這是封裝與解耦的典範。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved