Click here to Skip to main content
15,921,716 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, Thank you for spending some time to view my question. My question is how to listen an event???
Posted

This is how:

Having, for example, a class
C#
public class MyClass {

   public MyClass(/* ... */) {
      //...
   } 

   public event System.EventHandler<SomeEventArgs> SomeEvent; 

}
you can have an instance of this class and add an event handle to the invocation list of the event instance, once or several times:
C#
MyClass instance = MyClass(/* ... */);

//...

instance.SomeEvent += (sender, eventArgs) => {
    //... do something, optionally using sender or evenArgs
};

//...
// and, somewhere else, having a reference to the same instance:

instance.SomeEvent += (sender, eventArgs) => {
    DoSomethingElse(eventArgs);
};
where eventArgs is of the type SomeEventArgs, derived from System.EventArgs.

Please see:
http://msdn.microsoft.com/en-us/library/vstudio/awbftdfh.aspx[^],
http://msdn.microsoft.com/en-us/library/edzehd2t%28v=vs.110%29.aspx[^].

See also my past answers:
UserControl custom event[^],
WPF : How to Use Event in Custom Control[^].

Everything discussed above is fully applied to WPF events. At the same time, WPF events have advanced classification with quite advanced features which go well beyond the current topic, but this matter is good to know:
http://msdn.microsoft.com/en-us/library/ms753115%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 
v3
You don't "listen to" and event - you handle it with an Event Handler method.
Easy to do: in the designer, highlight the object you want to handle an event for, and look at the Properties pane.
Click the "Events" button - it looks like a little lightning bolt.
Double click the event name you want to handle and it will create an event handler for you, and link it to the object.

There are other ways: type the object instance name in the editor, followed by a '.'
Type the name of the Event, and then "+=" and press TAB twice.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900