Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Handling Events in WPF in an Easy and Short Hand Way

0.00/5 (No votes)
9 Jun 2015 1  
This tip is for WPF developers, understanding the usage of lambda expressions for handling the events instead of markup based or function based event handlers.

I would talk about the WPF events and how to handle them easily, perhaps you might already know how to handle them; XAML gives you a lot of good handy functions, but there are a lot of other good ways of doing the same.

Events in WPF

Events in WPF are similar to what we had in Console and Windows Forms. They provide us with notifications and procedures to handle the business logic based on what the state of 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.

I won't go into the depth of events in this tip, you can read more on MSDN.

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 would be using Visual C# for the purpose of this tip, it would be different as to what VB.NET would provide you 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 say, “When this happens, do that“. You tell your application to perform an action when something happens. The similar action is perform when a new email is received in your email clients, or when download is complete; if notification gets raised for that download complete. The attachment of the event to another function is pretty much simple, the only thing to worry is the required dependencies (the parameters or values or objects required to handle the event).

Look at the following code:

<Button Click="handleEvent">Click me</Button>

The above code is an XAML code (remember we are in WPF), the function to handle the event would be like this:

void handleEvent(object sender, RoutedEventArgs e) {
   // 1. sender is the Button object in this case, cast it
   // 2. e contains the related properties for the Click
   // Code here... Any code!
}

Now, the function handleEvent is attached to the Click event of the Button object. Remember that event needs to be raised in order to trigger that function. User, by interactions, triggers the event which in turn executes the function. You can think of this as:

  1. User clicks on Submit
  2. Application checks the input of the user
  3. Application saves the user data in file system

The event was click on button, which application used to handle and store the user's input. You can define your own conditions, by default no action is performed for you but application is itself aware of the click but does nothing.

Pretty much easy it is to handle the events in WPF, just embed the code in the XAML markup, and Visual Studio would generate 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 would explain how you can do that using back-end code.

Since we used Button for the previous example, I would use the same for this one. Attaching the event is as easy as 1, 2, 3…

button.Click += handleEvent; // 1. Attach the handler

void handleEvent(object sender, RoutedEventArgs e) { // 2. Create the function
   // Handle the event
}

Step 3 is the click event that is performed by the user. ;)

Easy isn’t it? (IMO, it is not! Look in the next section to make it even better!)

Simple Way…

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

A very simple way (IMO) to handle the event in WPF is like this:

myButton.Click += (sender, e) =>
{
   // Handle the event
}

Notice the above 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, so that is why we need to pass them. Parameters here have the same type that they had in the first code block. C# does the type casting for us and determines what type is being expected.

Simple, Yet Efficient Way...

Special thanks to comments below by tbayart and Sacha Barber, the above section was pretty simple, yet it had a problem of memory leakage. You can instead of writing hard-coded lambda expression, create an EventHandler delegate for the arguments and then use it to attach or detach the event handler. 

EventHandler<RoutedEventArgs> handler = (sender, e) => 
{
   // code here..
};

// Attaching the handler
myButton.Click += handler;
// Removing the handler
myButton.Click -= handler;

In the above code, the handler can be removed when no longer required. Whereas, in the above block, you cannot remove the handler, because it is hard-coded and attached and does not hold a definition or reference. 

This is more efficient as compared to the previous section as it allows us to write the handler in a memory-friendly way.

Points of Interest

The above is the simplest way anyone can handle the event in WPF and is very much short hand, because you leave everything to the context of the object itself. You skip one more step for casting the object, you also don’t have 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 will post more such helpful tips for WPF developers soon. :) Stay tuned.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here