#596 – Using Lamba Expressions When Declaring Event Handlers

When you attach an event handler to an event in WPF, you can use several different types of syntax for specifying the method that will serve as a handler.  This includes using both anonymous methods and lambda expressions.

Below are some examples of declaring an event handler using a lambda expression.

            // Use lambda expression to specify handler
            myButton.Click += (object s, RoutedEventArgs e) => Trace.WriteLine("Hey, you clicked a button");

            // You can omit the parameter types
            myTextBox.KeyDown += (s, e) => Trace.WriteLine("KEY pressed");

            // Expression can include a block of code
            myTextBox.KeyUp += (s, e) =>
                {
                    Trace.WriteLine("KEY released!");
                    Trace.WriteLine(string.Format("Key is {0}", e.Key));
                };
About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 233 other followers

%d bloggers like this: