Layout:兩個控件 iTextBox 和 ListBox
iTextBox
using System;
using System.Windows.Forms;
namespace DataChangeEvent
{
internal class iTextBox : TextBox
{
private string _oldValue;
public iTextBox()
{
// 註冊 KeyPress Event
KeyPress += iTextBox_KeyPress;
}
// Step3:宣告 DataChange Event
public event DataChangeEventHandler DataChange;
// Step4:建立 OnDataChange() 來觸發 DataChange Event
protected virtual void OnDataChange(DataChangeEventArgs e)
{
if (DataChange != null)
DataChange(this, e);
}
private void iTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Enter)
return;
// 值沒有變化情況下,就不需要觸發 DataChange Event
if (_oldValue == Text)
return;
// 紀錄新舊值
DataChangeEventArgs args = new DataChangeEventArgs(_oldValue, Text);
// 紀錄先舊值後,把新值設定為舊值
_oldValue = Text;
// 呼叫 Method 來觸發是事件
OnDataChange(args);
}
}
// Step2:建立 DataChangeEventHandler Delegate
public delegate void DataChangeEventHandler(object sender, DataChangeEventArgs e);
// Step1:建立 DataChangeEventArgs EventArgs,並宣告兩個 Property
public class DataChangeEventArgs : EventArgs
{
private string _oldValue;
public string OldValue { get => _oldValue;}
private string _newValue;
public string NewValue { get => _newValue;}
public DataChangeEventArgs(string oldValue, string newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}
}
}
DataChangeEvent
using System;
using System.Windows.Forms;
namespace DataChangeEvent
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 註冊 DataChange Event
iTextBox1.DataChange += iTextBox1_DataChange;
}
void iTextBox1_DataChange(object sender, DataChangeEventArgs e)
{
string oldValue = string.IsNullOrWhiteSpace(e.OldValue) ? "空值" : e.OldValue;
string info = $"觸發時間:{DateTime.Now} - OldValue:{oldValue} - NewValue:{e.NewValue}";
listBox1.Items.Add(info);
}
}
}
沒有留言:
張貼留言