Chapter 11. Events and Code-Behind

Unless your application consists solely of user interface (UI) elements (a loose XAML page might), you'll eventually need to associate program code with the UI elements. For example, the program will need to take action when the user clicks buttons, selects menu items, and clicks tools in the toolbar.

In WPF, the code that sits behind the user interface, responding to control events and performing other processing, is called the code-behind. Visual Studio makes writing code-behind easy. This chapter explains how to write code that handles control events so the application can respond to the user at run time.

Depending on what you're trying to accomplish and which language you're using, you have several options for connecting XAML objects to code-behind:

  • Using an event name attribute in XAML code

  • Adding event handlers at run time

  • Using the Handles clause (Visual Basic only)

The following sections describe these options and provide examples. Before you learn about event handlers and how to create them, however, it's worth taking a little time to learn about code-behind files.

Code-behind Files

Whenever you add a window to a project, Expression Blend or Visual Studio adds a corresponding code-behind file. The file has the same name as the XAML file with the extra extension cs (for C#) or vb (for Visual Basic). For example, when you create a new WPF project in C#, the project includes the initial window in the file Window1.xaml and the corresponding code-behind ...

Get WPF Programmer's Reference: Windows Presentation Foundation with C# 2010 and .NET 4 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.