跳到主要内容

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 we can code event handling for the button. We call this “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. Run GetStartedApp in debug mode.
A screenshot showing the location of the button to run a project in debug mode in Rider.
  1. Open the Debug Output tab in the bottom panel.
  2. In the running app window, click the Calculate button a few times.
  3. You should see “Click!” being printed in the debug output in Rider.

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