属性值更改后,以C#Windows窗体定义事件

时间:2018-12-18 16:55:03

标签: c# properties

我有一个非常基本的类,具有1个属性,如下所示:

public class NodeItem
{
    private object _Value;

    public object Value
    {
        get { return _Value; }
        set { _Value = value; }
    }
}

只要Value属性的值更改,如何定义事件?

1 个答案:

答案 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));
    }
}

Reference

用于订阅事件

void MyEventSubscription(object sender, CustomEventArgs a)  
{  
    // Do something useful here.  
}  

myClassInstance.PropertyChanged += MyEventSubscription;