Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have following class

public class ButtonChange
{
   private int _buttonState;
   public void  SetButtonState(int state)
   {
            _buttonState = state;
   }
}

I want to fire an event whenever _buttonState value changes, finaly I want to define an event handler in ButtonChange

Will you guys help me please??

P.S : I dont want to use INotifyPropertyChanged

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

How about:

public class ButtonChange
{
   // Starting off with an empty handler avoids pesky null checks
   public event EventHandler StateChanged = delegate {};

   private int _buttonState;

   // Do you really want a setter method instead of a property?
   public void SetButtonState(int state)
   {
       if (_buttonState == state)
       {
           return;
       }
       _buttonState = state;
       StateChanged(this, EventArgs.Empty);
   }
}

If you wanted the StateChanged event handler to know the new state, you could derive your own class from EventArgs, e.g. ButtonStateEventArgs and then use an event type of EventHandler<ButtonStateEventArgs>.

Note that this implementation doesn't try to be thread-safe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...