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.
The XAML file for the main window has a C# code-behind file associated with it. If you're using an IDE, you can find this file in the Solution Explorer - it is a sub-item of the
To change the code-behind for the main window:
- Open the
You will see some C# code like this:
public partial class MainWindow : Window
The partial class
MainWindow corresponds to the window object that is created by Avalonia UI as a result of the XAML you already have. You can find this class name in the XAML window tag:
To add an event handler for the button, follow this procedure:
- Locate the
MainWindowconstructor in the code-behind file for the main window (see above instructions).
- After the constructor add the following code:
public void ButtonClicked(object source, RoutedEventArgs args)
This will require some additional using statements:
- Switch to the XAML file and locate the
- Enter the click attribute at the end of the tag, as follows:
If you're using an IDE you will see the Avalonia UI Intellisense as you type.
- Run the app and click the button.
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 UI controls at runtime.