我有一个非常基本的类,具有1个属性,如下所示:
public class NodeItem
{
private object _Value;
public object Value
{
get { return _Value; }
set { _Value = value; }
}
}
只要Value
属性的值更改,如何定义事件?
答案 0 :(得分:1)
这是一个简单的例子
public event PropertyChangedEventHandler PropertyChanged;
private object _Value;
public object Value
{
get { return _value; }
set
{
_value = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged(value);
}
}
protected void OnPropertyChanged(object val)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(val));
}
}
用于订阅事件
void MyEventSubscription(object sender, CustomEventArgs a)
{
// Do something useful here.
}
myClassInstance.PropertyChanged += MyEventSubscription;