1.2.15 Basic Event Handlers for Buttons

A Button Can Trigger C# Code

A WPF application can contain a Button.

When the user activates the button, WPF raises a Click event.

The application can connect that event to an event-handler method.

At this stage, treat the event handler as:

the block of C# code that WPF runs when the button is clicked.

Detailed method design begins in the next module.

XAML Can Connect a Button to a Handler

A simplified example is:

XML / XAML
<Button
    Content="Show Player"
    Click="ShowPlayer_Click" />

The Click attribute identifies the handler name.

The visible button text comes from Content.

The Handler Exists in C# Code-Behind

A corresponding introductory handler can look like:

C#
private void ShowPlayer_Click(object sender, RoutedEventArgs e)
{
    statusText.Text = "Jordan";
}

Do not focus yet on sender and e.

Parameters are taught later.

For now, notice:

Plain text
button Click
    ↓
ShowPlayer_Click
    ↓
C# statements run

Keep the Event Handler Small

An introductory handler should perform the focused action required by the current application.

Avoid adding complex logic or redesigning the project.

Later method instruction will help you move behavior into focused methods when appropriate.

Event-Driven Flow Is Different from a Straight Startup Sequence

Some C# runs because the application starts.

An event handler waits until an event occurs.

Conceptually:

Plain text
application running
      ↓
user clicks button
      ↓
Click event
      ↓
handler executes

That is the basic WPF interaction you need at this point.