Skip to main content

Establishing events and responses

Our temperature converter app now looks reasonably functional, but doesn’t do anything yet. The next thing we need is for the Calculate button to be able to respond to a user action, such as a click.

Creating an event handler with code-behind

XAML files can be associated with a C# source file. This file is where you write event handling code for the button. This is called "code-behind".

  1. In your IDE, browse your project directory for Views → MainWindow.axaml → MainWindow.axaml.cs. This is the C# source file behind the main window XAML.
A screenshot showing the location of the main window's code-behind file in a file tree.
  1. Open MainWindow.axaml.cs.
  2. Locate the using directives at the top of the file. At this point, there should only be the single line using Avalonia.Controls;. Add these two using directives:
using Avalonia.Interactivity;
using System.Diagnostics;
  1. Locate the line public partial class MainWindow : Window further down the file. This class currently contains only the constructor for the main window, public MainWindow(). Below the constructor, add the following code:
private void Button_OnClick(object? sender, RoutedEventArgs e)
{
Debug.WriteLine("Click!");
}
  1. Your C# file should now look like this:
using Avalonia.Controls;
using Avalonia.Interactivity;
using System.Diagnostics;

namespace GetStartedApp.Views;

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_OnClick(object? sender, RoutedEventArgs e)
{
Debug.WriteLine("Click!");
}
}
  1. Switch to your XAML file, MainWindow.axaml.
  2. Locate <Button> near the bottom of the file.
  3. Add Click as an attribute to the <Button> tag and associate it with Button_OnClick, like so:
<Button HorizontalAlignment="Center" Click="Button_OnClick">Calculate</Button>

Checking the event handler works

To verify we’ve created the event handler correctly, we can check the debug output to confirm "Click!" is being printed when we click the Calculate button.

  1. Go to the Output window, located by default under the split view. From the "Show output from:" dropdown menu, select Debug.
  2. Run the app.
  3. In the running app window, click the Calculate button a few times.
  4. You should see "Click!" printed in the output window.
A screenshot showing the output screen in Visual Studio, with the word 'Click!' printed inside.

On the next page, you will learn how to implement the formula that converts temperatures from Celsius to Fahrenheit.

See also