-
Book Overview & Buying
-
Table Of Contents
Windows Application Development Cookbook
By :
Apart from adding controls to the page, it is necessary to introduce interaction with them, such as performing some actions after clicking on a button or choosing an item from a drop-down list. In this recipe, you will learn how to handle the event of pressing the button.
To use this recipe, you need the project from the previous recipe. It should contain the MainPage.xaml file with the added button.
To handle the Click event, you need to perform the following steps:
MainPage.xaml file in the Solution Explorer window.

Generating the method for handling the event of the button being clicked causes a modification, which is automatically introduced in both the MainPage.xaml and MainPage.xaml.cs files.
In the first file, with the XAML code describing the UI of the page, the Click property is automatically added to the Button element. It specifies the name of the method that is called when the user clicks on the button. The exemplary code is as follows:
<Page (...)>
<Grid (...)>
<Button
x:Name="button"
Content="Button"
HorizontalAlignment="Left"
Margin="164,242,0,0"
VerticalAlignment="Top"
Click="button_Click" />
</Grid>
</Page>
It is worth mentioning that the button_Click method must exist in the MainPage class (name set as x:Class in the Page element). This method is also automatically generated in the MainPage.xaml.cs file, as follows:
private void button_Click(object sender, RoutedEventArgs e) { }
The method has a name that contains the name of the button (button) as well as information about the kind of event (Click). It has two parameters:
sender: This is an object that represents the clicked element, which you can cast to Button as (Button)sendere: This represents the additional arguments regarding the operationTo specify operations that should be performed after pressing the button, you just need to add suitable C# code as the body of the button_Click method.
You could easily jump from the editor with the XAML code to the C#-based method definition by right-clicking its name defined in the .xaml file (within Click) and choosing Go To Definition from the context menu. Another solution is to click on such a name and press F12.
This way of handling the button being pressed is not the only possible one. Later in the book, you will learn how to use the data binding mechanism together with commands and the MVVM design pattern to improve the solution.