2012-02-21 8 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

が重複する可能性のように、このクラスを使用します(http://stackoverflow.com/questions/2448487/how- [C#でイベントをディスパッチする方法] –

+0

あなたの質問に含まれていない情報には、このイベントを処理するコードの説明があります。たとえば、イベントハンドラを自分で作成しているのですか、プロパティをUIにバインドしていますか?上に示したコードサンプルは、WPF/SL(およびその他の汎用フレームワーク)に固有です。 –

答えて

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; 
関連する問題