定义一个事件类型
public class PropertyValueChangedEventArgs : EventArgs { private string _propertyName; private object _oldValue; private object _newValue; public PropertyValueChangedEventArgs() : base() { } public PropertyValueChangedEventArgs(string propertyName, object oldValue, object newValue) : base() { _propertyName = propertyName; _oldValue = oldValue; _newValue = newValue; } public string PropertyName { get { return _propertyName; } set { _propertyName = value; } } public object OldValue { get { return _oldValue; } set { _oldValue = value; } } public object NewValue { get { return _newValue; } set { _newValue = value; } } }
定义一个事件测试使用的类
public class TestPropertyValueChangedEventArgs { private static readonly object uniqueLock = new object(); private static TestPropertyValueChangedEventArgs _Instance = null; public static TestPropertyValueChangedEventArgs Instance { get { lock (uniqueLock) { if (_Instance == null) { _Instance = new TestPropertyValueChangedEventArgs(); } } return _Instance; } } public event EventHandler<PropertyValueChangedEventArgs> PropertyChanged; private void OnPropertyChanged(string aPropertyName, object aOldValue, object aNewValue) { PropertyValueChangedEventArgs e = new PropertyValueChangedEventArgs(aPropertyName, aOldValue, aNewValue); if (PropertyChanged != null) { PropertyChanged(this, e); } } public void SetString(string strOldString, string strNewString) { OnPropertyChanged("Test_SetString", strOldString, strNewString); } }
注册事件
TestPropertyValueChangedEventArgs.Instance.PropertyChanged += new EventHandler<PropertyValueChangedEventArgs>(PropertyChanged);
使用事件
private void button2_Click(object sender, EventArgs e) { Thread thread = new Thread( () => { TestPropertyValueChangedEventArgs.Instance.SetString("_OLD2", "_NEW2"); } ); thread.Start(); } private void PropertyChanged(object sender, PropertyValueChangedEventArgs e) { if (e.PropertyName == "Test_SetString") { this.txtLog.Text += "收到设置属性Test_SetString事件,设置内容为:" + e.NewValue + "\n"; } }