2012-02-21 23 views
1

我希望运行一些会在某些计数器变化时发生的事件,例如,每次c#计数器变化事件

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

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

+1

的可能重复[如何分派在C#中的事件](http://stackoverflow.com/questions/2448487/how-在-c-sharp中调度事件) – 2012-02-21 09:37:27

+0

您的问题中未包含的一些信息是应该处理此事件的代码的解释。例如,你是自己编写一个事件处理程序,还是将该属性绑定到某个UI?您在上面显示的代码示例特定于WPF/SL(以及其他通用框架)。 – 2012-02-21 09:39:44

回答

3

你可能不得不做这样的事情在你的主程序:

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

所以,当counter.Counter的值发生变化,事件的用户将收到通知,并且执行(在我的例子中,SomeMethodYouWantToAssociate将是)。

private static void SomeMethodYouWantToAssociate(object sender, PropertyChangedEventArgs e) 
{ 
    // Some Magic inside here 
} 
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;