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

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: