Starter exercises
Now that you have built a temperature converter app, try these three exercises to test your understanding of Avalonia.
Exercise 1: Change an existing attribute
Challenge level: ★
Make the gridlines invisible in GetStartedApp.
Hint
You specified <Grid> in MainWindow.axaml.
Solution
In MainWindow.axaml, locate the <Grid> opening tag. Change the ShowGridLines attribute to False.
<Grid ShowGridLines="False" Margin="5"
ColumnDefinitions="120, 100"
RowDefinitions="Auto, Auto, Auto">
Exercise 2: Add a new attribute
Challenge level: ★★
Make it impossible for a user to input text into the Fahrenheit text box in GetStartedApp.
Hint (1st)
Check the API docs for more information on the TextBox control.
Hint (2nd)
Under the API reference for TextBox, you’ll find the attribute IsReadOnly.
Solution
In MainWindow.axaml, locate the <TextBox> tag for the Fahrenheit box. Add the IsReadOnly attribute, and set it to True.
<TextBox Grid.Row="1" Grid.Column="1" Margin="0 5" Text="0" Name="Fahrenheit" IsReadOnly="True"/>
Exercise 3: Program a new event response
Challenge level: ★★★
Make GetStartedApp calculate the temperature conversion as the user types.
Hint (1st)
Check the API docs for more information on the TextBox control.
Hint (2nd)
Under the API reference for TextBox, you’ll find the event TextChanged.
Hint (3rd)
Your event handler is defined in the C# code-behind MainWindow.axaml.cs. It is also referenced by the XAML file MainWindow.axaml.
Solution
- In MainWindow.axaml, locate the
<TextBox>tag for the Celsius box. Add theTextChangedevent, and give the event a name, e.g.Celsius_TextChanged.
<TextBox Grid.Row="0" Grid.Column="1" Margin="0 5" Text="0" TextChanged="Celsius_TextChanged" Name="Celsius"/>
- In MainWindow.axaml, delete the entire line starting
<Button>. It is no longer needed.
<Button HorizontalAlignment="Center" Click="Button_OnClick">Calculate</Button>
- In MainWindow.axaml.cs, locate the event handler line starting
private void. Change the event name fromButton_OnClickto whatever you named it in the XAML file, e.g.Celsius_TextChanged.
private void Celsius_TextChanged(object? sender, RoutedEventArgs e)
- Run the app to confirm that the value in the Fahrenheit box changes as you type in the Celsius box.
Congratulations! You have completed this starter tutorial for Avalonia!