c#柜台变更事件

时间:2012-02-21 09:29:47

标签: c# events event-handling

我希望运行一个事件,这个事件会在一些反击变化时发生,例如:每次

int counter;

更改其值,事件被提升。 我有类似MSDN的东西:

public class CounterChange:INotifyPropertyChanged
{
    private int counter;
    // Declare the event
    public event PropertyChangedEventHandler PropertyChanged;

    public CounterChange()
    {
    }

    public CounterChange(int value)
    {
        this.counter = value;
    }

    public int Counter
    {
        get { return counter; }
        set
        {
            counter = value;
            // Call OnPropertyChanged whenever the property is updated
            OnPropertyChanged("Counter");
        }
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

但不知道下一步是什么。如何从程序中提高增量,并将方法连接到这些事件。

2 个答案:

答案 0 :(得分:3)

您可能需要在主程序中执行以下操作:

var counter = new CounterChange(0);
counter.PropertyChanged += SomeMethodYouWantToAssociate;

因此,当counter.Counter的值发生变化时,将通知并执行事件的订阅者(在我的示例中,SomeMethodYouWantToAssociate将会出现)。

private static void SomeMethodYouWantToAssociate(object sender, PropertyChangedEventArgs e)
{
    // Some Magic inside here
}

答案 1 :(得分:0)

public class CounterClass
{
    private int counter;
    // Declare the event
    public event EventHandler CounterValueChanged;

    public CounterChange()
    {
    }

    public CounterChange(int value)
    {
        this.counter = value;
    }

    public int Counter
    {
        get { return counter; }
        set
        {
            //Chaeck if has really changed?
            if(counter != value)
            {
                counter = value;
                // Call CounterValueChanged whenever the property is updated
                //check if there are any subscriber to this event
                if(CounterValueChanged!=null)
                    CounterValueChanged(this, new EventArgs());
            }
        }
    }
}

并像这样使用这个类

CounterClass cnt = new CounterClass();
cnt.CounterValueChanged += MethodDelegateHere;