Click here to Skip to main content
15,884,793 members
Articles / Desktop Programming / WPF
Tip/Trick

Handling Events in WPF in an Easy and Short Hand Way

Rate me:
Please Sign up or sign in to vote.
3.54/5 (11 votes)
9 Jun 2015CPOL5 min read 26.4K   2   13
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:

XML
<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:

C#
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…

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
QuestionDO NOT DO THIS : Memory Leak City Pin
Sacha Barber10-Jun-15 5:54
Sacha Barber10-Jun-15 5:54 
AnswerRe: DO NOT DO THIS : Memory Leak City Pin
Afzaal Ahmad Zeeshan18-Jun-15 0:56
professionalAfzaal Ahmad Zeeshan18-Jun-15 0:56 
QuestionBad practice leading to Memory leaks Pin
tbayart10-Jun-15 4:15
professionaltbayart10-Jun-15 4:15 
AnswerRe: Bad practice leading to Memory leaks Pin
Afzaal Ahmad Zeeshan18-Jun-15 0:54
professionalAfzaal Ahmad Zeeshan18-Jun-15 0:54 
GeneralMy Vote of 5 Pin
aarif moh shaikh9-Jun-15 18:48
professionalaarif moh shaikh9-Jun-15 18:48 
Question+3 Thanks, but... Pin
Kevin Marois9-Jun-15 10:40
professionalKevin Marois9-Jun-15 10:40 
AnswerRe: +3 Thanks, but... Pin
Afzaal Ahmad Zeeshan9-Jun-15 10:44
professionalAfzaal Ahmad Zeeshan9-Jun-15 10:44 
GeneralRe: +3 Thanks, but... Pin
Kevin Marois9-Jun-15 10:52
professionalKevin Marois9-Jun-15 10:52 
GeneralRe: +3 Thanks, but... Pin
Afzaal Ahmad Zeeshan9-Jun-15 10:57
professionalAfzaal Ahmad Zeeshan9-Jun-15 10:57 
GeneralRe: +3 Thanks, but... Pin
PCoffey10-Jun-15 3:04
PCoffey10-Jun-15 3:04 
GeneralRe: +3 Thanks, but... Pin
PeejayAdams11-Jun-15 5:54
PeejayAdams11-Jun-15 5:54 
GeneralRe: +3 Thanks, but... Pin
Afzaal Ahmad Zeeshan11-Jun-15 6:26
professionalAfzaal Ahmad Zeeshan11-Jun-15 6:26 
GeneralRe: +3 Thanks, but... Pin
L Hills16-Jun-15 6:24
L Hills16-Jun-15 6:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.