Avalonia GUI framework#
Follow this tutorial to install and run your first graphical user interface (GUI).
GUI templates#
GUI applications typically require a lot of starter code and files. Templates ease GUI development. Let us install Avalonia templates.
Open any existing project or create a new one.
On the tool window bar on the left click
(Terminal).
Run the following command.
If your operating system terminal cannot run the dotnet command, then use a terminal inside your code editor.
dotnet new install Avalonia.Templates
You should get an output similar to:
Welcome to .NET ...!
---------------------
SDK Version: ...
...
The following template packages will be installed:
Avalonia.Templates
Success: Avalonia.Templates::... installed the following templates:
Template Name Short Name Language Tags
------------------ ------------------------- -------- -----------------------------------------
Avalonia .NET App avalonia.app [C#],F# Desktop/Xaml/Avalonia/Windows/Linux/macOS
...
The following templates might not work because their constraints are not met:
Avalonia TemplatedControl (avalonia.templatedcontrol) C#(identity: Avalonia.TemplatedControl)
Project capabiltities: No project was found at the path: /home/user/. This template can only be created inside the project.
...
You can ignore the last error about No project was found at the path.
dotnet new command installs project templates. Now we installed project templates for the Avalonia GUI framework that we can use upon creating a new project.
Rider Avalonia Plugin#
This plugin provides GUI preview during code development.
On the welcome screen, click
ConfigureClick
Plugins.Settingswindow will pop up withPluginsitem andInstalledtab being active.Click
Marketplacetab.Search for
avalonia.Install
AvaloniaRider.Restart your IDE.
If you had problems, look into the official instructions here.
Creating a GUI application#
On the welcome screen, click
New Solution.On the left, in
Custom Templates, clickAvalonia .NET app.On the right, you should see the settings for project creation.
Activate
Put solution and project in the same directory.You can leave the defaults for the solution and project name.
Click
Create.You should see a new window with
MainWindow.axaml.csandMainWindow.axamlfiles open.Run your project using F5.
You should see a new window opening with
Welcome to Avalonia!.Close this window to quit your application.
Changing how the GUI looks like#
Click
MainWindow.axaml.You should see some code. This code describes the layout of a window and data shown on it.
Fig. 4
Editor and Previewicon activated on the.axamleditor.#Preview the code using the
Editor and Previewicon as shown in Fig. 4.You should see the same window as when you last ran your program.
Change the text, e.g.,
Hi ๐.Tip
To use another emojis in your code, refer to Typing emojis.
Mainwindow.axaml is a AXAML file. AXAML is an Avalonia-specific XAML file.
- XAML
Extensible Application Markup Language (XAML) is a XML-based language that can be used to define user interface elements, data binding and events.
- XML
Extensible Markup Language (XML) is a markup language for storing, transmitting and reconstructing data.
- markup language
A code (text-encoding system) which specifies the structure and formatting of a document.
For example, HTML and Markdown.
In the following we will refer to AXAML file as XAML in short.
Template files and their purpose#
We have several files in our template. Let us look at the files relevant to implement our ideas:
MainWindow.axaml: We already discussed about this.Under the
axamlMainWindow.axaml.cs: This is called the code-behind file. This is the C# code, where we:describe how a window reacts to user events like mouse clicks
store or get data relevant to the window
setup the connection between the variables in AXAML file and the C# code.
Program.cs: This is the main program that initialized the GUI system. We will typically not touch this file.
Controlling GUI data from the code-behind#
Currently, data shown on our GUI is static. Typically the GUI will show data from a database or logic written in our program code. In the following we will reference a GUI element in the code-behind file make its content dynamic.
In the XAML, delete the greeting message and add the following instead:
<TextBlock Name="GreetingTextBlock"/>
This user interface element is a
TextBlock.TextBlockis one of several [built-in control elements][built-in-control] the Avalonia framework provides to us.We gave it a
Nameto reference it in the code-behind.Switch to code-behind and add the following line under
InitializeComponent():GreetingTextBlock.Text = "What did make you ๐ happy today?";
Run your code.
You should see the text that you set in code-behind.
A dynamic data example โ a diary prompter#
Our example is still static. Let us make it more dynamic by sketching an interactive diary program that prompts the user with random diary suggestions:
Replace the code we wrote in the code-behind with the following:
string[] basicEmotions =[ "๐ happy", "๐ข sad", "๐ก angry", "๐ฑ surprised", "๐คข disgusted", "๐จ fear" ] ; var randomEmotion = Random.Shared.GetItems(basicEmotions, 1)[0]; greetingTextBlock.Text = $"What made you {randomEmotion} today?";
Randomwill be red, because this identifier is not defined as default. Click it and use Ctrl. to fix it automatically by selectingImport missing references in file.Run your code.
Each time you run it, you will see another prompt.
In the code above, we define an array of basic emotion strings and then choose one using the random item chooser Random.Shared.GetItems. This function takes an array and chooses n random elements and returns these n elements as an array. In our case n is 1. Therefore, we have to select this only element using the index 0.
Getting input from the GUI#
Now we can output data to the user, now we will integrate the userโs input to our program logic.
Let us put up a button that changes the prompt. Browse the built-in controls and search for a button and come back.
You probably landed on the Button like me.
GUI programs typically handle user inputs by executing up a function whenever the user interacts with the GUI, e.g., a mouse click. Using this event, we can react to the user in our program logic.
First we will add the control to the XAML and then the corresponding function to the code-behind.
Let us use the example from the
Buttonexample and modify it for example as follows and add to our XAML like this:<Button Click="ClickHandler">Change prompt</Button> <TextBlock Name="GreetingTextBlock"/>
ClickHandlerwill react to userโs click. Text between the> <is buttonโs text content.After adding it, you should get an error about:
Property Content is set more than once
The
Windowelement allows only a single object under it, but we have two objects. We have to put these elements into a container element that supports many objects. These are design decisions made by the designers of Avalonia and we have to adhere to that.Change the lines as follows:
<StackPanel> <Button Click="ClickHandler">Change prompt</Button> <TextBlock Name="greetingTextBlock"/> </StackPanel>
The preview should show you the new layout.
TroubleshootingIf the preview is frozen:
try the icon on the top right of the preview window.
run your project
make sure your XAML does not have any errors.
You will see
ClickHandler(red), because this symbol is not defined.Click the red symbol and use Ctrl. to
Create event handler.You will be sent to the code-behind and you will see a new function called
ClickHandler.The content of this function will be executed whenever the user interacts with the button. We will now create a new prompt whenever the user clicks the button. So move code from the
MainWindow()function to theClickHandleras follows:private void ClickHandler(object? sender, RoutedEventArgs e) { string[] basicEmotions =[ "๐ happy", "๐ข sad", "๐ก angry", "๐ฑ surprised", "๐คข disgusted", "๐จ fear" ] ; var randomEmotion = Random.Shared.GetItems(basicEmotions, 1)[0]; GreetingTextBlock.Text = $"What made you {randomEmotion} today?"; }
Run your program. You should see a new prompt each time you click the button.
Visual XAML editor#
The Avalonia plugin for Rider does not feature where you can design your GUI with by dragging and dropping visual elements. When you first sketch your UI, a visual drag-and-drop UI designer is very helpful. You can use the following web-based editor for this purpose:
After editing, only copy the <Grid/> component that is included under the <Page/>, because this XAML editor is designed for Visual Studio.
Most of the controls in this web-based editor is available in Avalonia, but not every. Moreover, the design may look slightly differently in Avalonia. If you want to see interactive examples of Avalonia UI elements, take a look at Avalonia UI playground.
I recommend using xaml.io only for initial design and preview, because the web-based editor may add many unnecessary attributes that may overcomplicate the XAML and lead to errors. Writing XAML manually may train you to write clean XAML with meaningful structure using grids (instead of manually placed UI elements.)
Tip
Use Layout elements for the UI layout, e.g., use a StackPanel to evenly distribute Buttons in an area. This helps to keep symmetry in your user interface.
Upgrading .NET templates#
Templates installed using dotnet are typically in steady development, so the template you have installed today may have a version mismatch with a package you install today, which leads to an error in the IDE. If this happens, then you can upgrade templates as follows:
Open a new project based on the Avalonia template.
Click
. A template is based on package/s. You should see Avalonia packages with version numbers. Grey numbers indicate the current project number. The turquoise numbers on the right show the latest version. If they are higher, then the template can be updated,
Open a terminal in the IDE and run the following command:
dotnet new update
This upgrade only upgrades the template, so only new projects will get new versions of the packages included in the template. If you want to upgrade packages in an existing project, follow section Upgrading .NET packages in the project.
Close the project and create a new one and check the version numbers.
If nothing has changed, then the repository for templates may not have been updated. Follow Upgrading .NET packages in the project to manually update the packages in your project and try updating the templates after ~one week.
Upgrading .NET packages in the project#
Note that each project can have different versions of packages installed.
Appendix#
For this tutorial I used the following documentation. Peek into them if you run into errors.