2017年2月17日 星期五

EventHandler 自訂事件

UserControl1.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public partial class UserControl1 : UserControl
{
    /// <summary>
    /// 建立事件處理
    /// </summary>
    new public event EventHandler TextChanged;
        
    /// <summary>
    /// 事件處理函數
    /// </summary>
    protected void OnTextChanged()
    {
        // 如果有建立事件監聽,則Invoke
        TextChanged?.Invoke(this.textBox1, new EventArgs());
    }
    public UserControl1()
    {
        InitializeComponent();
    }

    /// <summary>
    /// 使用者控制項 的 TextBox 預設 TextChanged 事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        OnTextChanged();
    }
}


Form1.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // 針對使用者控制項新增自訂的 TextChanged 事件
        this.userControl11.TextChanged += UserControl11_TextChanged;
    }

    /// <summary>
    /// 使用者控制項新增自訂的 TextChanged 事件處理函數
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void UserControl11_TextChanged(object sender, EventArgs e)
    {
        if (sender is TextBox)
        {
            TextBox tb = sender as TextBox;
            label1.Text = tb.Text;
        }
    }
}

沒有留言 :

張貼留言