Handling Events in WPF Easily

I will explain the WPF events and how to handle them easily, perhaps you already understand how to handle them. XAML gives you many good, handy functions, but there are many other good ways of doing it.

Events in WPF

Events in WPF are similar to what we had in Console and Windows Forms applications. They provide us with notifications and procedures to handle the business logic based on what the state of the application is. They allow us to manage what to happen when the application is starting, what to do when the application is closing and when the user interacts with the application.

Interaction includes the button clicks, input value change, window resize and many other similar processes that can be handled to ensure that our business logic is always applied. Validation and other checks can be easily applied to check the values.

Handling the events

Although handling the events is another function, we require a function to perform (or get triggered) when a certain event is triggered.

Note: Please note that I will be using Visual C# for the purpose of this article, it will be different from what VB.NET provides as intuition and library resource, so try to follow Visual C# and not VB.NET at the moment.

In C#, you can handle the event by attaching a function to it. It is similar to saying, “When this happens, do that“. You tell your application to perform an action when something happens. The similar action is done when a new email is received in your email clients, or when a download is complete if notification is raised for that download complete. The attachment of the event to another function is quite simple, the only thing to worry about is the required dependencies (the parameters or values or objects required to handle the event).

Look at the following code:

  1. <Button Click="handleEvent">Click me</Button>  
The preceding code is a XAML code (remember we are in WPF), the function to handle the event will be like this:
  1. void handleEvent(object sender, RoutedEventArgs e) {  
  2.    // 1. sender is the Button object, cast it  
  3.    // 2. e contains the related properties for the Click  
  4.    // Code here... Any code!  
  5. }  
Now, the function handleEvent is attached to the Click event of the Button object. Remember that the event needs to be raised to trigger that function.

It is quite easy to handle the events in WPF, just embed the code in the XAML markup and Visual Studio generates the back-end code. Write what you want to be done and you're good to go!

Using back-end code

As you know, you can do anything with back-end code. You can also attach the event handler to the control's event using the back-end code. In this section, I will explain how to do that using back-end code.

Since we used a Button for the previous example, I will use that for this one. Attaching the event is as easy as 1, 2, 3.
  1. button.Click += handleEvent; // 1  
  2.   
  3. void handleEvent(object sender, RoutedEventArgs e) { // 2  
  4.    // Handle the event  
  5. }  
Step 3 is the click event that is done by the user.

Easy, isn't it? No? If you think the preceding way is difficult, then look in the next section to make it even better!

Simple way

This section is the actual section that I wanted to talk about. The simple way to handle the events is WPF. It uses the lambda expression to generate the delegate functions that in turn are executed when the event is raised. If you are unclear as to what lambda expression or delegate functions are, I will suggest that, before continuing, learn them from the links I have provided.

A very simple way to handle the event in WPF is as in the following.
  1. myButton.Click += (sender, e) =>   
  2. {  
  3.    // Handle the event  
  4. }  
Notice the preceding expressions. It is a simple lambda expression being resolved as a delegate function with two parameters (sender and e). The parameters are required by the event handler itself, that is why we need to them.

Simple, and efficient way... 

Well perhaps, above mentioned is a very compact way for handling the events. But, there is a problem with that, memory leak. That is because user cannot remove subscription to that event, you cannot do 
  1. myButton.Click -= (sender, e) {  
  2.    // code  
  3. }  
Nope, that doesn't work. Because the reference to the previous handler is not similar to the one that is being used now to unsubscribe the event. For this, we must use the EventHandler delegate to make sure that we can later unsubscribe the events also. To use it, we would create a delegate, the Args, and use the object to subscribe or unsubscribe the event later when we no longer need to handle the event. It is a memory efficient way, look below, 
  1. EventHandler<RoutedEventArgs> handler = (sender, e) =>   
  2. {  
  3.    // Code..  
  4. };  
  5.   
  6. // Attaching the event handler  
  7. myButton.Click += handler;  
  8.   
  9. // Removing the event handler  
  10. myButton.Click -= handler;  
The above code would work in a memory efficient way. We can handle the event, and when we no longer need it we can unsubscribe the event also. Thus, enabling us to write memory-efficient software and simple and straight-forward WPF application. :) 
 
Points of Interest

The preceding is the simplest way to handle the events in WPF and is a shorthand way, because you leave everything to the context of the object itself. You skip one more step for casting the object, you also don't need to create different functions with different appended names such as “myButton_Click”, “myButton_MouseEnter”. All you need to do is just create a lambda expression and use it as the event handler. Pretty much simple, isn't it?

That's all for now. I hope I might have helped you out in making programming WPF applications easier. I would post more of such helpful tips for WPF developers soon. Stay tuned.