Respond to an Event
There are a number of ways you can implement actions in an Avalonia application. On this page, you will see how to use one of the simplest: how to write event handling code for a button click.
To start, you will write a button click event handler that does not interact with any of the other controls.
Code-Behind
XAML files can have C# source files associated with it referred to as by "code-behind". Code-behind is used to access
named controls and handle events for its associated XAML. When using an IDE, you can find this file in
the Solution Explorer as a sub-item of the .axaml
file.
To change the code-behind for MainWindow
:
- Open the
MainWindow.axaml.cs
file
You should see C# code like this:
using Avalonia.Controls;
namespace GetStartedApp.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
The partial class MainWindow
corresponds to the Window
created by Avalonia as a result of the XAML you already
have. The namespace and class name must be the same in both XAML and code-behind. You can find this class name in the
root XAML tag:
<UserControl x:Class="GetStartedApp.Views.MainWindow"
...>
</UserControl>
To add an event handler for the Button
, follow this procedure:
- Locate the
MainWindow
constructor in the code-behind file (see above instructions). - After the constructor, add the following code:
private void Button_OnClick(object? sender, RoutedEventArgs e)
{
Debug.WriteLine("Click!");
}
This will require the following using statements:
using Avalonia.Interactivity;
using System.Diagnostics;
- Switch to the XAML file and locate the
<Button>
tag. - Enter the
Click
attribute at the end of the tag, as follows:
<Button Grid.Row="2" Grid.Column="1" Click="Button_OnClick">Calculate</Button>
- Run the app in Debug mode and click the Calculate button.
- Rider
- Visual Studio
You should see the result on the Output window for Debug, like this:
You should see the result on the Output window for Debug, like this:
On the next page, you will see how to use code-behind to read and change the properties of Avalonia controls at runtime.