Pages

Friday 2 December 2011

Lesson 4. Event Handling

This lesson will deal with events and how to handle them. You will be using  event handling in every step of application development as you start developing bigger applications. So best get familiar with it right now :)

We will be going through the following topics.

1. Accessing Events for a control
2. Event handling through code.

Step 1: Accessing Events for a control.

1. Create a new Silverlight Application and drag a Button control on to the Grid.
    Right Click ->   Properties  ->   The property pane opens to the right side of the screen.
    Click on the lightning symbol , which represents events.



 
Different controls have different events associated with them. As you can notice, there are many events associated with this Button control. 

2. To add an event handler for an event, just type a new event handler name beside the event.



3. If you double click the event handler name , you will be taken to the code file and the event handler stub  will be automatically generated.


 4.  You can write your functionality inside this event handler.  For now, i am going to display a message that reads HI.   Add             MessageBox.Show("HI"); inside buttonclick

5. When you  press F5 to Run the application , a message box pops up when you click the button.


You can change the properties of other controls using the event handlers. For example, you could change the background color of the application when you click a button. 


Step 2 :  Event handling through code.

You can add an event handler directly from code instead of doing it from the Properties pane.  In the previous lesson (Lesson 3), we added an event handler for the completed event. 


There are 2 steps to handle an event ,  First step is to associate the event with a handler  and the second step is to write the functionality in the handler.

1.  We add an event handler to a control using the  += operator.   In reality, it uses the concept of delegates {but that concept is not really needed right now}
  
2.  Add a new button to the Grid, and to add a click event to our button, we simply write
     button2.click += .      inside the MainPage()  constructor.
    Visual studio provides auto completion for the event handler by pressing the TAB key twice.

3. Write the MessageBox.Show("Hi")  code inside this method, and press F5 to Run

4. The output will be the same as earlier. 

5. If for some reason you want to remove the event handler at a later stage, then you can use the  -= operator. 

This way , you can handle all the events for any control.  For a more detailed explanation and demo, watch the video.


No comments:

Post a Comment