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

#579 – Adding an Event Handler for a User Interface Element

The simplest way to handle an event for a user interface element, like a Button or a Label, is to add a handler for the event to a single control.

Let’s say that we have some UI elements defined in XAML as follows.

    <StackPanel Orientation="Vertical">
        <Label Content="Some good movies:"/>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Lawrence of Arabia" FontWeight="Bold"/>
            <Label Content="David Lean"/>
            <Button Content="Like" Padding="8,0"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Schindler's List" FontWeight="Bold"/>
            <Label Content="Steven Spielberg"/>
            <Button Content="Like" Padding="8,0"/>
        </StackPanel>
    </StackPanel>


You add a handler for a single UI element by specifying the name of the event and handler (method) in XAML.

        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Lawrence of Arabia" FontWeight="Bold"/>
            <Label Content="David Lean"/>
            <Button Content="Like" Padding="8,0" Click="btn_LawrenceLike"/>
        </StackPanel>

And then adding code for the handler in the code-behind file.

        private void btn_LawrenceLike(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("You like Lawrence of Arabia");
        }

#501 – Sharing an Event Handler Across Multiple Controls, Method II

If you want to use an event handler to handle an event originating from several controls, you can specify the handler for each control and then use the RoutedEventArgs.Source property to determine the control that originated the event.

You can also just specify a handler for the Button.Click event on the parent panel that holds all of the buttons.  It will handle all Click events that originate lower down in the visual tree.

    <StackPanel ButtonBase.Click="Button_Click">
        <Button Content="Keaton" HorizontalAlignment="Center" Padding="10,5" Margin="5"/>
        <Button Content="Chaplin" HorizontalAlignment="Center" Padding="10,5" Margin="5"/>
        <Button Content="Arbuckle" HorizontalAlignment="Center" Padding="10,5" Margin="5"/>
    </StackPanel>

The event handler is the same as before–you can check the RoutedEventArgs.Source property to determine the Button that originated the event.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Get at originator of event using RoutedEventArgs.Source property

            Button b = e.Source as Button;
            MessageBox.Show(string.Format("You clicked on {0} button", b.Content));
        }

#500 – Sharing an Event Handler Across Multiple Controls, Method 1

You can use the same event handler for more than one control by specifying the handler for each control and pointing to the same event handler code.

In the example below, we have three buttons, each of which wires up a handler for the Click event, but using the same handler (Button_Click).

    <StackPanel>
        <Button Content="Keaton" HorizontalAlignment="Center" Padding="10,5" Margin="5"
                Click="Button_Click"/>
        <Button Content="Chaplin" HorizontalAlignment="Center" Padding="10,5" Margin="5"
                Click="Button_Click"/>
        <Button Content="Arbuckle" HorizontalAlignment="Center" Padding="10,5" Margin="5"
                Click="Button_Click"/>
    </StackPanel>

In the Button_Click event handler, we can check the Source property of the RoutedEventArgs parameter to determine which button sent us the event.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Get at originator of event using RoutedEventArgs.Source property

            Button b = e.Source as Button;
            MessageBox.Show(string.Format("You clicked on {0} button", b.Content));
        }

#190 – Adding an Event Handler to a Control Using Blend

You’ll generally use Visual Studio to create and edit event handling code for a WPF application.  But you can also add event handling code using Blend.

To add an event handler using Blend, start by left-clicking to select the control for which you want to add an event (e.g. a Button).

Now, click on the Events icon on the Properties tab to see a list of the control’s events.

Next, find the event for which you want to add an event handler and double-click in the empty area next to the event name.  The event name will be filled in and you’ll be taken to the code editor for the new handler.

If you go back to look at the XAML, you’ll also see the new event handler defined there.

#189 – Adding an Event Handler to a Control Using Visual Studio

An event handler is code that executes in response to a user-initiated event–for example, code that executes when a user clicks a button.

In Visual Studio, you can add a new event handler in several ways.  You could edit the XAML directly and enter the name of a handler, or you can just double-click in the Properties window.

To add a new event handler from the properties window, start by left-clicking to select the control for which you want to add an event (e.g. a Button).

Next, find the desired event on the Events tab in the Properties window (e.g. Click).

Double-click in the empty area to the right of the event name, generating a name for the new handler (e.g. button1_Click)..

..and you’ll be taken to the code editor, where the body of the new event handler is located.

The name of the handler also now appears in XAML.

#70 – Specifying Event Handlers in XAML

In addition to setting property values, you can also wire up event handlers in XAML.  You do this by specifying the name of the event and the name of the method in your code-behind that should be called when the event fires.

Here’s an example:

<Button Name="btnClickMe" Content="Click Me" Height="23" Width="75" Click="Button_Click"/>

This wires up this button’s Click event to the Button_Click method in the containing window’s code-behind (.cs) file.

private void Button_Click(object sender, RoutedEventArgs e)
{
}

Adding the event handler in XAML is equivalent to doing it in code as follows:

this.btnClickMe.Click += new RoutedEventHandler(Button_Click);