2012-02-21 25 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;