Skip to content

Commit 4126ee1

Browse files
Merge pull request #862 from AvaloniaUI/861-improve-starter-tutorial-with-better-input-behaviour-for-minus-signs
Add optional improvement to starter exercises
2 parents 6eff19d + 02191ce commit 4126ee1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

docs/get-started/starter-tutorial/exercises.mdx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,51 @@ Make **GetStartedApp** calculate the temperature conversion as the user types.
106106
4. Run the app to confirm that the value in the Fahrenheit box changes as you type in the Celsius box.
107107
</details>
108108

109+
<details>
110+
<summary>Optional: Further improvement</summary>
111+
112+
To allow the Celsius box to accept an empty state or a standalone minus sign, you can adjust the code-behind like so:
113+
114+
1. In **MainWindow.axaml.cs**, locate the event handler `private void Celsius_TextChanged`. Add a new `if` condition to allow input to be empty or a minus sign only.
115+
116+
```csharp
117+
if (string.IsNullOrEmpty(Celsius.Text) || Celsius.Text == "-")
118+
{
119+
Fahrenheit.Text = "";
120+
}
121+
```
122+
123+
2. Change the original `double` parser to start `else if`, as it is now the second condition.
124+
125+
```csharp
126+
else if (double.TryParse(Celsius.Text, out double C))
127+
```
128+
129+
3. Your event handler should now look like this:
130+
131+
```csharp
132+
private void Celsius_TextChanged(object? sender, RoutedEventArgs e)
133+
{
134+
if (string.IsNullOrEmpty(Celsius.Text) || Celsius.Text == "-")
135+
{
136+
Fahrenheit.Text = "";
137+
}
138+
else if (double.TryParse(Celsius.Text, out double C))
139+
{
140+
var F = C * (9d / 5d) + 32;
141+
Fahrenheit.Text = F.ToString("0.0");
142+
}
143+
else
144+
{
145+
Celsius.Text = "0";
146+
Fahrenheit.Text = "0";
147+
}
148+
}
149+
```
150+
151+
4. Run the app to confirm that you can now delete all input from the Celsius box, or input a standalone minus sign, without the box resetting to 0. The Fahrenheit box displays nothing when this is the case. This improvement allows you to type in a negative number without interruption.
152+
</details>
153+
109154
Congratulations! You have completed this starter tutorial for Avalonia!
110155

111156
## Further reading

0 commit comments

Comments
 (0)