Create event c# (not invoke or define)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fredrick Rivers

    #1

    Create event c# (not invoke or define)

    Hi, I need to create a NEW event on c#: I need to execute a command when a local variable CHANGES, I know how to define, execute, etc events that are already stored in VS (buttonClicked, etc...) Is there a simple way to do this?
    Many thanks for your time.
  • Leito
    New Member
    • Apr 2010
    • 58

    #2
    I don't know any mean to do that, but there should be a defined event (like buttonClicked.. .) that triggers the change of your local variable, isn't it ?

    Comment

    • Christian Binder
      Recognized Expert New Member
      • Jan 2008
      • 218

      #3
      You an't trigger an event when a local variable changes, but you can use a property instead of a local variable and there you can trigger the event.

      Code:
      //Define the event
      event Action LocalVarChanged;
      
      int _localVar = 0;
      
      //Create a property for your local var
      LocalVar {
        get { return _localVar; }
        set {
          _localVar = value;
          //Trigger the event
          if(event != null)
            event();
        }
      }

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        Christian's answer is exactly how to do this, if you want a specific event for a specific property.

        If you want a single event for all your properties (with the EventArgs telling you which property changed), there's already an interface designed to do this for you: INotifyProperty Changed.

        Implementing that interface properly, and adding the invocation code to all your properties, will let you catch when any property changes, and react appropriately. This is useful for objects that will be used in ObservableColle ctions.

        Comment

        Working...