#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));
                };
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: