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