跳到主要内容

Adding a control

The first step for our temperature converter app is to add a control. By “controls”, we mean UI elements that allow interaction with your app. Some examples of controls are buttons, sliders, checkboxes or menus.

For more information on controls, see the Controls reference page.

Inserting a button

Let’s try replacing the text in the app with a button.

  1. Stop the app if it is still running.
  2. In the file MainWindow.axaml, locate this line:
<TextBlock Text="{Binding Greeting}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  1. Replace the entire line with this:
<Button>Calculate</Button>
  1. Run the app or check the previewer. You should now see a Calculate button in the app window.
  2. You can try hovering over or clicking the button to see how its appearance changes.
A screenshot of an app running in a window, with the button aligned left.

Setting the button's attributes

Controls in Avalonia use XML attributes to specify their presentation and behavior.

Your Calculate button is currently aligned against the left edge of the window. This is because the default value of the HorizontalAlignment attribute is Left. Let’s change this attribute to put the button in the center instead.

  1. In the file MainWindow.axaml, go to the line you added for the button:
<Button>Calculate</Button>
  1. Add the HorizontalAlignment attribute to the <Button> tag. Set it to Center.
<Button HorizontalAlignment="Center">Calculate</Button>
  1. Run the app or check the previewer. You should see that the Calculate button moves to the center of the window.
A screenshot of an app running in a window, with the button aligned center.

On the next page of this tutorial, you will learn how to add multiple elements to your app using layout controls.