Pre-operative assessment in .NET MAUI
The questions a patient answers before an operation, on iPhone and Android, with .NET MAUI and Lily: the same questionnaire and rules as the web tutorial.
What you'll build
The web tutorial's questionnaire, as one C# app for iOS and Android: five short sections (about you, heart and lungs, medicines, allergies and anaesthetics), then a screen to check the answers before they are sent. A date of birth typed in parts, a weight and a height in the patient's own units, a list of medicines that grows as the patient adds them, the steps they have done, and an error summary that takes them to each missing answer. The answers are saved on the phone as they go. About an hour.
It asks; it does not judge. No answer gives the patient a grade or a score: the anaesthetist assigns the ASA grade at the assessment, from these answers and their own findings.
Before you start
You need the .NET 11 SDK with the MAUI workload (dotnet workload install maui),
and Xcode for iOS or the Android SDK for Android. LilyDesignSystem.Maui is not on
NuGet yet, so the app references it from a clone of the repository, beside the app:
git clone https://github.com/LilyDesignSystem/lily-design-system
dotnet new maui -n PreOperativeAssessment
mkdir PreOperativeAssessment.Tests
cd PreOperativeAssessment
rm App.xaml App.xaml.cs AppShell.xaml AppShell.xaml.cs MainPage.xaml MainPage.xaml.cs
rm -r Resources/Styles The app is written in C#, so the template's XAML pages and styles go. Each code block below
is one whole file in PreOperativeAssessment, or in PreOperativeAssessment.Tests beside it; replace the file the template made where
the names match.
Step 1: The project
PreOperativeAssessment.csproj
<Project Sdk="Microsoft.NET.Sdk">
<!-- The pre-operative assessment app: the patient's questionnaire, drawn with Lily's MAUI controls. -->
<PropertyGroup>
<TargetFrameworks>net11.0-android;net11.0-ios</TargetFrameworks>
<OutputType>Exe</OutputType>
<RootNamespace>PreOperativeAssessment</RootNamespace>
<UseMaui>true</UseMaui>
<SingleProject>true</SingleProject>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<ApplicationTitle>Before your operation</ApplicationTitle>
<ApplicationId>com.example.preoperativeassessment</ApplicationId>
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<ApplicationVersion>1</ApplicationVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">17.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">24.0</SupportedOSPlatformVersion>
</PropertyGroup>
<ItemGroup>
<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#005EB8" />
<MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#005EB8" BaseSize="128,128" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Maui.Controls" Version="11.0.10" />
</ItemGroup>
<ItemGroup>
<!-- Until LilyDesignSystem.Maui is on NuGet: a project reference into your clone of the monorepo. -->
<ProjectReference Include="../lily-design-system/lily-design-system-maui/src/LilyDesignSystem.Maui/LilyDesignSystem.Maui.csproj" />
</ItemGroup>
</Project> Step 2: Write the words
Every word the app shows is in one file, so translating the app touches no page. The order of a date's parts is a word too: a reader elsewhere may write the year first. The step statuses are words, so a step never says where the patient is by colour or a tick alone.
Words.cs
namespace PreOperativeAssessment;
/// <summary>Every word the app shows, in one place, so the app can be translated without touching a page.</summary>
public static class Words
{
/// <summary>The language the app writes in, for formatting dates.</summary>
public const string Locale = "en-GB";
/// <summary>The clinic's time zone, IANA: whose "today" a date of birth is checked against.</summary>
public const string TimeZone = "Europe/London";
public const string Title = "Before your operation";
public const string Intro = "These questions help the team plan your anaesthetic. The clinic reads your answers before your assessment.";
public const string Saved = "Your answers are saved on this device as you go.";
public const string Restored = "We filled in the answers you saved on this device.";
public const string Keep = "Keep my answers";
public const string StartAgain = "Start again";
public const string Steps = "Questions";
public static readonly string[] StepNames = ["About you", "Heart and lungs", "Medicines", "Allergies", "Anaesthetics", "Check your answers"];
public static string Status(string status) => status switch
{
"finished" => "Done",
"in-progress" => "Now",
_ => "To do",
};
public const string Back = "Back";
public const string Next = "Continue";
public const string Send = "Send to the clinic";
public const string Problem = "There is a problem";
public static string Said(Answer answer) => answer switch
{
Answer.Yes => "Yes",
Answer.No => "No",
Answer.NotSure => "Not sure",
_ => "Not answered",
};
public const string DateLabel = "Date of birth";
public const string Day = "Day";
public const string Month = "Month";
public const string Year = "Year";
public const string DateHint = "For example, 3 2 1949";
/// <summary>The parts in the order this app's readers write a date: "ymd", "dmy" or "mdy".</summary>
public const string DateOrder = "dmy";
public const string WeightLabel = "Your weight";
public const string Weight = "Weight";
public const string WeightUnit = "Weight unit";
public const string HeightLabel = "Your height";
public const string Height = "Height";
public const string HeightUnit = "Height unit";
public const string Kilograms = "kilograms";
public const string Pounds = "pounds";
public const string Centimetres = "centimetres";
public const string Inches = "inches";
public const string Operation = "What operation are you having?";
public const string OperationHint = "In your own words, as the hospital told you";
public const string CouldBePregnant = "Could you be pregnant?";
public const string HighBloodPressure = "Have you been told you have high blood pressure?";
public const string BreathlessOnStairs = "Do you get chest pain or very short of breath climbing one flight of stairs?";
public const string BloodThinner = "Do you take medicine to thin your blood?";
public const string BloodThinnerName = "Which medicine?";
public const string BloodThinnerHint = "For example, warfarin or apixaban";
public const string AnyMedicines = "Do you take any medicines?";
public const string AnyMedicinesHint = "Include ones you buy yourself, and inhalers, creams and injections";
public const string Medicines = "Your medicines";
public static string Medicine(int n) => $"Medicine {n}";
public const string AddMedicine = "Add a medicine";
public static string RemoveMedicine(int n) => $"Remove medicine {n}";
public static string MedicineAdded(int n) => $"Medicine {n} added";
public static string MedicineRemoved(int n) => $"Medicine {n} removed";
public const string MedicineName = "Name";
public const string MedicineDose = "How much, and how often";
public const string AnyAllergies = "Are you allergic to anything?";
public const string AnyAllergiesHint = "Medicines, foods, plasters, latex or anything else";
public const string Allergies = "Your allergies";
public static string Allergy(int n) => $"Allergy {n}";
public const string AddAllergy = "Add an allergy";
public static string RemoveAllergy(int n) => $"Remove allergy {n}";
public static string AllergyAdded(int n) => $"Allergy {n} added";
public static string AllergyRemoved(int n) => $"Allergy {n} removed";
public const string Substance = "What are you allergic to?";
public const string Reaction = "What happens?";
public const string Severe = "Has it ever made it hard to breathe, or made your face or throat swell?";
public const string SevereShort = "Severe reaction";
public const string AnaesthesiaBefore = "Have you had an anaesthetic before?";
public const string AnaesthesiaProblem = "Did you have a problem with it?";
public const string AnaesthesiaProblemDetails = "What happened?";
public const string FamilyAnaesthesiaProblem = "Has a blood relative had a serious problem with an anaesthetic?";
public static readonly Dictionary<string, string> Errors = new()
{
["birth-date"] = "Enter your date of birth as a real date that has passed",
["weight"] = "Enter your weight",
["height"] = "Enter your height",
["operation"] = "Enter the operation you are having",
["could-be-pregnant"] = "Answer whether you could be pregnant",
["high-blood-pressure"] = "Answer the question about blood pressure",
["breathless-on-stairs"] = "Answer the question about chest pain or breathlessness",
["blood-thinner"] = "Answer the question about blood-thinning medicine",
["any-medicines"] = "Answer whether you take any medicines",
["medicine-list"] = "Add the medicines you take, or answer no",
["any-allergies"] = "Answer whether you are allergic to anything",
["allergy-list"] = "Add what you are allergic to, or answer no",
["anaesthesia-before"] = "Answer whether you have had an anaesthetic before",
["anaesthesia-problem"] = "Answer whether you had a problem with it",
["family-anaesthesia-problem"] = "Answer the question about your family",
};
public const string Change = "Change";
public static string ChangeSection(string section) => $"Change {section}";
public const string SentTitle = "Your answers have been sent";
public const string SentBody = "Thank you. Bring your medicines, or a list of them, to your assessment.";
} Step 3: Hold the answers
Every question starts unanswered, which is not the same as "no". The page changes the answers in place as the patient answers, so a field keeps its focus; a follow-up's answer is kept while the patient changes their mind, and left out when it is sent.
Answers.cs
namespace PreOperativeAssessment;
// What the patient says. Every question starts unanswered, which is not the same as "no". The page changes these in place as
// the patient answers; the rules read them.
public enum Answer { Unanswered, Yes, No, NotSure }
public sealed class Quantity
{
public string Magnitude { get; set; } = "";
public string Unit { get; set; } = "";
}
public sealed class Medicine
{
public string Name { get; set; } = "";
public string Dose { get; set; } = "";
}
public sealed class Allergy
{
public string Substance { get; set; } = "";
public string Reaction { get; set; } = "";
/// <summary>Did it ever make it hard to breathe, or swell the face or throat?</summary>
public Answer Severe { get; set; }
}
public sealed record Answers
{
/// <summary>YYYY-MM-DD once all three parts are filled, else "".</summary>
public string BirthDate { get; set; } = "";
public Quantity Weight { get; set; } = new() { Unit = "kg" };
public Quantity Height { get; set; } = new() { Unit = "cm" };
public string Operation { get; set; } = "";
/// <summary>Asked of everyone: "no" covers anyone who cannot be.</summary>
public Answer CouldBePregnant { get; set; }
public Answer HighBloodPressure { get; set; }
public Answer BreathlessOnStairs { get; set; }
public Answer BloodThinner { get; set; }
/// <summary>Asked only when BloodThinner is Yes.</summary>
public string BloodThinnerName { get; set; } = "";
public Answer AnyMedicines { get; set; }
/// <summary>Asked only when AnyMedicines is Yes.</summary>
public List<Medicine> Medicines { get; set; } = [];
public Answer AnyAllergies { get; set; }
/// <summary>Asked only when AnyAllergies is Yes.</summary>
public List<Allergy> Allergies { get; set; } = [];
public Answer AnaesthesiaBefore { get; set; }
/// <summary>Asked only when AnaesthesiaBefore is Yes.</summary>
public Answer AnaesthesiaProblem { get; set; }
/// <summary>Asked only when AnaesthesiaProblem is Yes.</summary>
public string AnaesthesiaProblemDetails { get; set; } = "";
public Answer FamilyAnaesthesiaProblem { get; set; }
} Step 4: Write the rules, with tests
The rules are pure functions, the same as the web tutorial's: what is sent, what is missing,
and whether a date of birth is a real day that has passed. "Today" is the clinic's day, in
its time zone, not the phone's. FormParts.IsCalendarDate comes from Lily's pure core,
so 31 February is never a birthday.
Rules.cs
using System.Globalization;
using LilyDesignSystem.Maui.Core;
namespace PreOperativeAssessment;
public enum Section { About, Heart, Medicines, Allergies, Anaesthesia }
/// <summary>
/// The rules, as pure functions, the same as the web tutorial's. None of them grades the patient: the anaesthetist assigns
/// the ASA grade, from these answers and their own findings. These say what to send and what is missing.
/// </summary>
public static class Rules
{
private const double Pound = 0.45359237;
private const double Inch = 0.0254;
private static double? Positive(string magnitude) =>
double.TryParse(magnitude, NumberStyles.Float, CultureInfo.InvariantCulture, out var n) && double.IsFinite(n) && n > 0 ? n : null;
/// <summary>Weight in kilograms, or null when it is not a number above zero.</summary>
public static double? Kilograms(Quantity weight) => Positive(weight.Magnitude) is { } n ? (weight.Unit == "lb" ? n * Pound : n) : null;
/// <summary>Height in metres, or null when it is not a number above zero.</summary>
public static double? Metres(Quantity height) => Positive(height.Magnitude) is { } n ? (height.Unit == "in" ? n * Inch : n / 100) : null;
/// <summary>What is sent: an answer the patient can no longer see is left out, and so is an entry with no name.</summary>
public static Answers Sent(Answers a)
{
var problem = a.AnaesthesiaBefore == Answer.Yes ? a.AnaesthesiaProblem : Answer.Unanswered;
return a with
{
BloodThinnerName = a.BloodThinner == Answer.Yes ? a.BloodThinnerName : "",
Medicines = a.AnyMedicines == Answer.Yes ? [.. a.Medicines.Where(m => !string.IsNullOrWhiteSpace(m.Name))] : [],
Allergies = a.AnyAllergies == Answer.Yes ? [.. a.Allergies.Where(x => !string.IsNullOrWhiteSpace(x.Substance))] : [],
AnaesthesiaProblem = problem,
AnaesthesiaProblemDetails = problem == Answer.Yes ? a.AnaesthesiaProblemDetails : "",
};
}
/// <summary>Today, YYYY-MM-DD, in the clinic's time zone: a date of birth is checked against the clinic's day, not the phone's.</summary>
public static string Today(string timeZone, DateTimeOffset? now = null) =>
TimeZoneInfo.ConvertTime(now ?? DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(timeZone))
.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
/// <summary>Whether a date of birth is a real day on or before today. The date field checks only that its parts are numbers.</summary>
public static bool IsBirthDate(string iso, string onOrBefore) =>
iso.Length == 10 && FormParts.IsCalendarDate(iso) && string.CompareOrdinal(iso, onOrBefore) <= 0;
/// <summary>The questions in a section that still need an answer, by their id. <paramref name="on"/> is today, from Today.</summary>
public static List<string> Missing(Section section, Answers a, string on)
{
var missing = new List<string>();
void Need(string id, bool answered)
{
if (!answered) missing.Add(id);
}
switch (section)
{
case Section.About:
Need("birth-date", IsBirthDate(a.BirthDate, on));
Need("weight", Kilograms(a.Weight) is not null);
Need("height", Metres(a.Height) is not null);
Need("operation", !string.IsNullOrWhiteSpace(a.Operation));
Need("could-be-pregnant", a.CouldBePregnant != Answer.Unanswered);
break;
case Section.Heart:
Need("high-blood-pressure", a.HighBloodPressure != Answer.Unanswered);
Need("breathless-on-stairs", a.BreathlessOnStairs != Answer.Unanswered);
Need("blood-thinner", a.BloodThinner != Answer.Unanswered);
break;
case Section.Medicines:
Need("any-medicines", a.AnyMedicines != Answer.Unanswered);
Need("medicine-list", a.AnyMedicines != Answer.Yes || Sent(a).Medicines.Count > 0);
break;
case Section.Allergies:
Need("any-allergies", a.AnyAllergies != Answer.Unanswered);
Need("allergy-list", a.AnyAllergies != Answer.Yes || Sent(a).Allergies.Count > 0);
break;
case Section.Anaesthesia:
Need("anaesthesia-before", a.AnaesthesiaBefore != Answer.Unanswered);
Need("anaesthesia-problem", a.AnaesthesiaBefore != Answer.Yes || a.AnaesthesiaProblem != Answer.Unanswered);
Need("family-anaesthesia-problem", a.FamilyAnaesthesiaProblem != Answer.Unanswered);
break;
}
return missing;
}
} The tests build the app's own Answers.cs and Rules.cs on plain .NET,
with no device or emulator.
PreOperativeAssessment.Tests/PreOperativeAssessment.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk">
<!-- The rules, tested on plain .NET with no device: the app's own Answers.cs and Rules.cs, and Lily's pure core. -->
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Compile Include="../PreOperativeAssessment/Answers.cs" />
<Compile Include="../PreOperativeAssessment/Rules.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../lily-design-system/lily-design-system-maui/src/LilyDesignSystem.Maui.Core/LilyDesignSystem.Maui.Core.csproj" />
</ItemGroup>
</Project> PreOperativeAssessment.Tests/RulesTests.cs
using PreOperativeAssessment;
namespace PreOperativeAssessment.Tests;
// The rules, checked without a device: each test names one rule.
public class RulesTests
{
private static Quantity Q(string magnitude, string unit) => new() { Magnitude = magnitude, Unit = unit };
[Fact]
public void WeightIsInKilogramsAndPoundsAreConverted()
{
Assert.Equal(70, Rules.Kilograms(Q("70", "kg")));
Assert.Equal(69.853, Rules.Kilograms(Q("154", "lb"))!.Value, 3);
Assert.Null(Rules.Kilograms(Q("0", "kg")));
Assert.Null(Rules.Kilograms(Q("heavy", "kg")));
}
[Fact]
public void HeightIsInMetres()
{
Assert.Equal(1.7, Rules.Metres(Q("170", "cm"))!.Value, 9);
Assert.Equal(1.7018, Rules.Metres(Q("67", "in"))!.Value, 4);
}
[Fact]
public void ADateOfBirthIsARealDayThatHasPassed()
{
Assert.True(Rules.IsBirthDate("1949-02-03", "2026-11-27"));
Assert.False(Rules.IsBirthDate("1949-02-31", "2026-11-27"));
Assert.False(Rules.IsBirthDate("2030-01-01", "2026-11-27"));
Assert.False(Rules.IsBirthDate("", "2026-11-27"));
}
[Fact]
public void TodayIsTheClinicsDay()
{
var lateInLondon = DateTimeOffset.Parse("2026-12-31T23:50:00Z", System.Globalization.CultureInfo.InvariantCulture);
Assert.Equal("2026-12-31", Rules.Today("Europe/London", lateInLondon));
Assert.Equal("2027-01-01", Rules.Today("Asia/Tokyo", lateInLondon));
}
[Fact]
public void AHiddenAnswerIsNotSent()
{
var s = Rules.Sent(new Answers
{
BloodThinner = Answer.No,
BloodThinnerName = "warfarin",
AnyMedicines = Answer.Yes,
Medicines = [new() { Name = "Ramipril", Dose = "5 mg daily" }, new()],
AnaesthesiaBefore = Answer.No,
AnaesthesiaProblem = Answer.Yes,
AnaesthesiaProblemDetails = "Sick",
});
Assert.Equal("", s.BloodThinnerName);
Assert.Equal(["Ramipril"], s.Medicines.Select(m => m.Name));
Assert.Equal(Answer.Unanswered, s.AnaesthesiaProblem);
Assert.Equal("", s.AnaesthesiaProblemDetails);
}
[Fact]
public void NotSureIsAnAnswerButAnEmptyListAfterYesIsNot()
{
Assert.Equal(["any-medicines"], Rules.Missing(Section.Medicines, new Answers(), "2026-11-27"));
Assert.Equal(["medicine-list"], Rules.Missing(Section.Medicines, new Answers { AnyMedicines = Answer.Yes }, "2026-11-27"));
Assert.Empty(Rules.Missing(Section.Medicines, new Answers { AnyMedicines = Answer.NotSure }, "2026-11-27"));
}
[Fact]
public void TheFirstSectionNamesEachMissingAnswerInOrder()
{
Assert.Equal(
["birth-date", "weight", "height", "operation", "could-be-pregnant"],
Rules.Missing(Section.About, new Answers(), "2026-11-27"));
}
} Check your work: from the folder above the app, run dotnet test PreOperativeAssessment.Tests. All seven tests pass.
Step 5: Save a draft
The answers are saved on the phone as the patient goes, with MAUI's Preferences, so closing the app loses nothing, and cleared once they are sent.
Draft.cs
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PreOperativeAssessment;
/// <summary>The answers so far, kept on this device as the patient goes, so closing the app loses nothing. Cleared when sent.</summary>
public sealed class Draft
{
private const string Key = "pre-operative-answers";
private static readonly JsonSerializerOptions Options = new() { Converters = { new JsonStringEnumConverter() } };
private static readonly string Blank = JsonSerializer.Serialize(new Answers(), Options);
public Answers? Load()
{
var json = Preferences.Default.Get<string?>(Key, null);
if (json is null) return null;
try
{
return JsonSerializer.Deserialize<Answers>(json, Options);
}
catch (JsonException)
{
return null;
}
}
public void Save(Answers answers)
{
var json = JsonSerializer.Serialize(answers, Options);
if (json == Blank) Clear();
else Preferences.Default.Set(Key, json);
}
public void Clear() => Preferences.Default.Remove(Key);
} Step 6: Ask a question
Yes, no or not sure: "Not sure" is an answer the clinic can act on, and a guess is not. The
options are MAUI radio buttons; the question, hint and error are read before them, as a
legend is on the web. A follow-up sits straight after "Yes". A line of text goes in Lily's Field, which gives the Entry its spoken name.
Questions.cs
using LilyDesignSystem.Maui;
namespace PreOperativeAssessment;
/// <summary>The app's question views, made from Lily's controls and MAUI's own.</summary>
public static class Questions
{
private static int groups;
/// <summary>
/// A question answered yes, no or not sure, as MAUI radio buttons. The question, hint and error are read before the
/// options, as a legend is on the web: Lily's Field names one control, and a group of radio buttons is several. A follow-up,
/// when given, sits straight after "Yes" and shows only while "Yes" is chosen; the rules leave its answer out otherwise.
/// </summary>
public static View Question(string question, Answer value, Action<Answer> changed, string? hint = null, string? error = null, View? followUp = null)
{
var stack = new VerticalStackLayout { Spacing = 4, StyleClass = ["question"] };
stack.Children.Add(new Label { Text = question, StyleClass = ["field-label"] });
if (hint is not null) stack.Children.Add(new Label { Text = hint, StyleClass = ["field-description"] });
if (error is not null) stack.Children.Add(new Label { Text = error, StyleClass = ["field-error"] });
var group = $"question-{++groups}";
foreach (var option in new[] { Answer.Yes, Answer.No, Answer.NotSure })
{
var radio = new RadioButton { Content = Words.Said(option), GroupName = group, IsChecked = value == option, MinimumHeightRequest = 48 };
radio.CheckedChanged += (_, e) =>
{
if (!e.Value) return;
changed(option);
if (followUp is not null) followUp.IsVisible = option == Answer.Yes;
};
stack.Children.Add(radio);
if (option == Answer.Yes && followUp is not null)
{
followUp.IsVisible = value == Answer.Yes;
followUp.Margin = new Thickness(16, 0, 0, 8);
stack.Children.Add(followUp);
}
}
return stack;
}
/// <summary>A line of text the patient writes, in Lily's Field, which gives the Entry its spoken name.</summary>
public static View Text(string label, string text, Action<string> changed, string? hint = null, string? error = null)
{
var entry = new Entry { Text = text };
entry.TextChanged += (_, e) => changed(e.NewTextValue ?? "");
return new Field { Label = label, Description = hint, Error = error, Control = entry };
}
/// <summary>An error under a list, for "add one, or answer no".</summary>
public static View ListError(string? message) =>
new Label { Text = message, IsVisible = message is not null, StyleClass = ["field-error"] };
} Step 7: The five sections
Each section is one method. Each question is passed to target with the id the
rules use, so the error summary can scroll to it. DateField joins its parts
into an ISO date only when every part is a number; QuantityInput keeps the
number and its unit together, and tells the app when the unit changes. RepeatableFieldset is the "add another" pattern: each medicine is a named group with
its own remove button, and the screen reader hears each add and remove in the app's words.
Sections.cs
using LilyDesignSystem.Maui;
using static PreOperativeAssessment.Questions;
namespace PreOperativeAssessment;
/// <summary>
/// The five sections, one method each. Each changes the answers in place, and passes each question's view to
/// <c>target</c> with the id the rules use, so the error summary can scroll to it.
/// </summary>
public static class Sections
{
public static IEnumerable<View> AboutYou(Answers a, Action saved, IReadOnlyDictionary<string, string> errors, Func<string, View, View> target)
{
var date = new DateField
{
Label = Words.DateLabel,
DayLabel = Words.Day,
MonthLabel = Words.Month,
YearLabel = Words.Year,
Order = Words.DateOrder,
Description = Words.DateHint,
Value = a.BirthDate,
Error = errors.GetValueOrDefault("birth-date"),
};
date.PropertyChanged += (_, e) =>
{
if (e.PropertyName != nameof(DateField.Value)) return;
a.BirthDate = date.Value;
saved();
};
yield return target("birth-date", date);
yield return target("weight", Quantity(Words.WeightLabel, Words.Weight, Words.WeightUnit,
[new("kg", Words.Kilograms), new("lb", Words.Pounds)], a.Weight, saved, errors.GetValueOrDefault("weight")));
yield return target("height", Quantity(Words.HeightLabel, Words.Height, Words.HeightUnit,
[new("cm", Words.Centimetres), new("in", Words.Inches)], a.Height, saved, errors.GetValueOrDefault("height")));
yield return target("operation", Text(Words.Operation, a.Operation, v => { a.Operation = v; saved(); }, Words.OperationHint, errors.GetValueOrDefault("operation")));
yield return target("could-be-pregnant", Question(Words.CouldBePregnant, a.CouldBePregnant, v => { a.CouldBePregnant = v; saved(); },
error: errors.GetValueOrDefault("could-be-pregnant")));
}
private static QuantityInput Quantity(string label, string magnitude, string unit, QuantityUnit[] units, Quantity q, Action saved, string? error)
{
var input = new QuantityInput { Label = label, MagnitudeLabel = magnitude, UnitLabel = unit, Units = units, Unit = q.Unit, Error = error };
input.Magnitude.Text = q.Magnitude;
input.Magnitude.TextChanged += (_, e) => { q.Magnitude = e.NewTextValue ?? ""; saved(); };
input.UnitChanged += (_, _) => { q.Unit = input.Unit; saved(); };
return input;
}
public static IEnumerable<View> HeartAndLungs(Answers a, Action saved, IReadOnlyDictionary<string, string> errors, Func<string, View, View> target)
{
yield return target("high-blood-pressure", Question(Words.HighBloodPressure, a.HighBloodPressure, v => { a.HighBloodPressure = v; saved(); },
error: errors.GetValueOrDefault("high-blood-pressure")));
yield return target("breathless-on-stairs", Question(Words.BreathlessOnStairs, a.BreathlessOnStairs, v => { a.BreathlessOnStairs = v; saved(); },
error: errors.GetValueOrDefault("breathless-on-stairs")));
yield return target("blood-thinner", Question(Words.BloodThinner, a.BloodThinner, v => { a.BloodThinner = v; saved(); },
error: errors.GetValueOrDefault("blood-thinner"),
followUp: Text(Words.BloodThinnerName, a.BloodThinnerName, v => { a.BloodThinnerName = v; saved(); }, Words.BloodThinnerHint)));
}
public static IEnumerable<View> Medicines(Answers a, Action saved, IReadOnlyDictionary<string, string> errors, Func<string, View, View> target)
{
var list = new RepeatableFieldset<Medicine>
{
Legend = Words.Medicines,
NewItem = () => new Medicine(),
ItemLegend = Words.Medicine,
AddLabel = Words.AddMedicine,
RemoveLabel = Words.RemoveMedicine,
Max = 30,
AddedLabel = Words.MedicineAdded,
RemovedLabel = Words.MedicineRemoved,
ItemView = (m, _) => new VerticalStackLayout
{
Spacing = 12,
Children =
{
Text(Words.MedicineName, m.Name, v => { m.Name = v; saved(); }),
Text(Words.MedicineDose, m.Dose, v => { m.Dose = v; saved(); }),
},
},
Items = a.Medicines,
};
list.ItemsChanged += (_, _) => saved();
var followUp = new VerticalStackLayout { Spacing = 8, Children = { ListError(errors.GetValueOrDefault("medicine-list")), target("medicine-list", list) } };
yield return target("any-medicines", Question(Words.AnyMedicines, a.AnyMedicines, v => { a.AnyMedicines = v; saved(); },
Words.AnyMedicinesHint, errors.GetValueOrDefault("any-medicines"), followUp));
}
public static IEnumerable<View> Allergies(Answers a, Action saved, IReadOnlyDictionary<string, string> errors, Func<string, View, View> target)
{
var list = new RepeatableFieldset<Allergy>
{
Legend = Words.Allergies,
NewItem = () => new Allergy(),
ItemLegend = Words.Allergy,
AddLabel = Words.AddAllergy,
RemoveLabel = Words.RemoveAllergy,
Max = 30,
AddedLabel = Words.AllergyAdded,
RemovedLabel = Words.AllergyRemoved,
ItemView = (x, _) => new VerticalStackLayout
{
Spacing = 12,
Children =
{
Text(Words.Substance, x.Substance, v => { x.Substance = v; saved(); }),
Text(Words.Reaction, x.Reaction, v => { x.Reaction = v; saved(); }),
Question(Words.Severe, x.Severe, v => { x.Severe = v; saved(); }),
},
},
Items = a.Allergies,
};
list.ItemsChanged += (_, _) => saved();
var followUp = new VerticalStackLayout { Spacing = 8, Children = { ListError(errors.GetValueOrDefault("allergy-list")), target("allergy-list", list) } };
yield return target("any-allergies", Question(Words.AnyAllergies, a.AnyAllergies, v => { a.AnyAllergies = v; saved(); },
Words.AnyAllergiesHint, errors.GetValueOrDefault("any-allergies"), followUp));
}
public static IEnumerable<View> Anaesthesia(Answers a, Action saved, IReadOnlyDictionary<string, string> errors, Func<string, View, View> target)
{
var problem = target("anaesthesia-problem", Question(Words.AnaesthesiaProblem, a.AnaesthesiaProblem, v => { a.AnaesthesiaProblem = v; saved(); },
error: errors.GetValueOrDefault("anaesthesia-problem"),
followUp: Text(Words.AnaesthesiaProblemDetails, a.AnaesthesiaProblemDetails, v => { a.AnaesthesiaProblemDetails = v; saved(); })));
yield return target("anaesthesia-before", Question(Words.AnaesthesiaBefore, a.AnaesthesiaBefore, v => { a.AnaesthesiaBefore = v; saved(); },
error: errors.GetValueOrDefault("anaesthesia-before"), followUp: problem));
yield return target("family-anaesthesia-problem", Question(Words.FamilyAnaesthesiaProblem, a.FamilyAnaesthesiaProblem,
v => { a.FamilyAnaesthesiaProblem = v; saved(); }, error: errors.GetValueOrDefault("family-anaesthesia-problem")));
}
} Step 8: Check the answers
The answers as they will be sent, through the same Sent rule, so a hidden answer
is not shown either. Each section has a change button whose spoken name says which section.
CheckAnswers.cs
using System.Globalization;
using LilyDesignSystem.Maui;
namespace PreOperativeAssessment;
/// <summary>The answers as they will be sent, so a hidden answer is not shown either, with a change button per section.</summary>
public static class CheckAnswers
{
public static IEnumerable<View> Views(Answers answers, Action<int> change)
{
var s = Rules.Sent(answers);
var unanswered = Words.Said(Answer.Unanswered);
// A date of birth is a calendar date, not a moment: DateOnly has no time zone to move it a day.
var date = DateOnly.TryParseExact(s.BirthDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d)
? d.ToString("D", CultureInfo.GetCultureInfo(Words.Locale))
: unanswered;
var units = new Dictionary<string, string>
{
["kg"] = Words.Kilograms, ["lb"] = Words.Pounds, ["cm"] = Words.Centimetres, ["in"] = Words.Inches,
};
string Quantity(Quantity q) => q.Magnitude.Length == 0 ? unanswered : $"{q.Magnitude} {units.GetValueOrDefault(q.Unit, q.Unit)}";
static string Joined(string separator, params string[] parts) => string.Join(separator, parts.Where(p => p.Length > 0));
var sections = new List<(string Term, string Value)>[]
{
[
(Words.DateLabel, date),
(Words.WeightLabel, Quantity(s.Weight)),
(Words.HeightLabel, Quantity(s.Height)),
(Words.Operation, s.Operation.Length > 0 ? s.Operation : unanswered),
(Words.CouldBePregnant, Words.Said(s.CouldBePregnant)),
],
[
(Words.HighBloodPressure, Words.Said(s.HighBloodPressure)),
(Words.BreathlessOnStairs, Words.Said(s.BreathlessOnStairs)),
(Words.BloodThinner, Joined(": ", Words.Said(s.BloodThinner), s.BloodThinnerName)),
],
[(Words.AnyMedicines, Words.Said(s.AnyMedicines)), .. s.Medicines.Select((m, i) => (Words.Medicine(i + 1), Joined(", ", m.Name, m.Dose)))],
[
(Words.AnyAllergies, Words.Said(s.AnyAllergies)),
.. s.Allergies.Select((x, i) => (Words.Allergy(i + 1), Joined(", ", x.Substance, x.Reaction, x.Severe == Answer.Yes ? Words.SevereShort : ""))),
],
[
(Words.AnaesthesiaBefore, Words.Said(s.AnaesthesiaBefore)),
.. s.AnaesthesiaBefore == Answer.Yes
? [(Words.AnaesthesiaProblem, Joined(": ", Words.Said(s.AnaesthesiaProblem), s.AnaesthesiaProblemDetails))]
: Array.Empty<(string, string)>(),
(Words.FamilyAnaesthesiaProblem, Words.Said(s.FamilyAnaesthesiaProblem)),
],
};
for (var step = 0; step < sections.Length; step++)
{
var index = step;
var name = Words.StepNames[step];
var heading = new Label { Text = name, FontSize = 20, FontAttributes = FontAttributes.Bold, VerticalOptions = LayoutOptions.Center };
SemanticProperties.SetHeadingLevel(heading, SemanticHeadingLevel.Level2);
var changeButton = new Button { Text = Words.Change, HorizontalOptions = LayoutOptions.End };
SemanticProperties.SetDescription(changeButton, Words.ChangeSection(name));
changeButton.Clicked += (_, _) => change(index);
var header = new Grid { ColumnDefinitions = [new ColumnDefinition(GridLength.Star), new ColumnDefinition(GridLength.Auto)] };
header.Add(heading, 0);
header.Add(changeButton, 1);
var list = new SummaryList { Label = name };
foreach (var (term, value) in sections[step]) list.Children.Add(new SummaryListItem { Term = term, Value = value });
yield return new VerticalStackLayout { Spacing = 8, Children = { header, list } };
}
}
} Step 9: Put the questionnaire together
One section a screen, with the steps above it. Continue checks the section: when something
is missing, ErrorSummary lists it and moves the screen reader to its title, and each
problem scrolls to its question.
QuestionnairePage.cs
using LilyDesignSystem.Maui;
using LilyDesignSystem.Maui.Core;
namespace PreOperativeAssessment;
/// <summary>
/// The questionnaire: one section a screen, with the steps above it, an error summary when a section is not finished, and the
/// check-your-answers screen last. Each change is saved on this device. The page is drawn again when the step or the problems
/// change; a typed answer changes the answers in place, so a field keeps its focus.
/// </summary>
public class QuestionnairePage : ContentPage
{
private readonly Draft draft = new();
private readonly ScrollView scroll = new();
private readonly Dictionary<string, View> targets = [];
private Answers answers;
private bool restored;
private bool sent;
private int step;
private List<string> problems = [];
public QuestionnairePage()
{
var saved = draft.Load();
answers = saved ?? new Answers();
restored = saved is not null;
BackgroundColor = Colors.White;
Content = scroll;
Render();
}
private void Save()
{
if (!sent) draft.Save(answers);
}
private View Target(string id, View view) => targets[id] = view;
private void Go(int next)
{
problems = [];
step = next;
Render();
}
private void Render()
{
targets.Clear();
var page = new VerticalStackLayout { Spacing = 24, Padding = new Thickness(20, 16) };
var title = new Label { Text = Words.Title, FontSize = 34, FontAttributes = FontAttributes.Bold };
SemanticProperties.SetHeadingLevel(title, SemanticHeadingLevel.Level1);
page.Children.Add(title);
if (sent)
{
page.Children.Add(new LilyAlert { Kind = AlertKind.Success, Heading = Words.SentTitle, Message = Words.SentBody });
Show(page);
return;
}
if (step == 0)
{
page.Children.Add(new Label { Text = Words.Intro });
// Lily's InsetText is the words; the rail at its leading edge is the app's drawing.
var inset = new Grid { ColumnDefinitions = [new ColumnDefinition(4), new ColumnDefinition(GridLength.Star)], ColumnSpacing = 12 };
inset.Add(new BoxView { Color = Colors.Black }, 0);
inset.Add(new InsetText { Text = Words.Saved }, 1);
page.Children.Add(inset);
}
if (restored)
{
page.Children.Add(new LilyAlert { Message = Words.Restored, Politeness = Politeness.Polite });
var keep = new Button { Text = Words.Keep };
keep.Clicked += (_, _) => { restored = false; Render(); };
var again = new Button { Text = Words.StartAgain };
again.Clicked += (_, _) =>
{
answers = new Answers();
draft.Clear();
restored = false;
Go(0);
};
page.Children.Add(new HorizontalStackLayout { Spacing = 12, Children = { keep, again } });
}
page.Children.Add(new StepList { Label = Words.Steps, Steps = Words.StepNames, Current = step, StatusLabel = Words.Status });
if (problems.Count > 0)
{
var summary = new ErrorSummary { Title = Words.Problem };
foreach (var id in problems)
summary.Problems.Add(new Problem(Words.Errors[id], () => _ = scroll.ScrollToAsync(targets[id], ScrollToPosition.Start, true)));
page.Children.Add(summary);
}
var heading = new Label { Text = Words.StepNames[step], FontSize = 26, FontAttributes = FontAttributes.Bold };
SemanticProperties.SetHeadingLevel(heading, SemanticHeadingLevel.Level2);
page.Children.Add(heading);
var errors = problems.ToDictionary(id => id, id => Words.Errors[id]);
var views = (Section?)(step < 5 ? (Section)step : null) switch
{
Section.About => Sections.AboutYou(answers, Save, errors, Target),
Section.Heart => Sections.HeartAndLungs(answers, Save, errors, Target),
Section.Medicines => Sections.Medicines(answers, Save, errors, Target),
Section.Allergies => Sections.Allergies(answers, Save, errors, Target),
Section.Anaesthesia => Sections.Anaesthesia(answers, Save, errors, Target),
_ => CheckAnswers.Views(answers, Go),
};
foreach (var view in views) page.Children.Add(view);
var buttons = new Grid { ColumnDefinitions = [new ColumnDefinition(GridLength.Auto), new ColumnDefinition(GridLength.Star), new ColumnDefinition(GridLength.Auto)] };
if (step > 0)
{
var back = new Button { Text = Words.Back };
back.Clicked += (_, _) => Go(step - 1);
buttons.Add(back, 0);
}
var forward = new Button { Text = step < 5 ? Words.Next : Words.Send, StyleClass = ["primary"] };
forward.Clicked += (_, _) =>
{
if (step == 5)
{
draft.Clear();
sent = true;
Render();
return;
}
problems = Rules.Missing((Section)step, answers, Rules.Today(Words.TimeZone));
if (problems.Count == 0) Go(step + 1);
else Render();
};
buttons.Add(forward, 2);
page.Children.Add(buttons);
Show(page);
}
private void Show(View page)
{
scroll.Content = page;
_ = scroll.ScrollToAsync(0, 0, false);
}
} Step 10: Style Lily's hooks and start the app
Lily's controls set no colour, size or font: the app styles them by their class hooks, as a web theme styles the kebab-case classes. The app draws Lily's light theme only, so it asks the system for light too, and the status bar stays readable in dark mode.
AppStyles.cs
namespace PreOperativeAssessment;
/// <summary>
/// The app's styles for Lily's class hooks. Lily's controls set no colour, size or font; an app styles them by StyleClass, as
/// the web themes style the kebab-case classes.
/// </summary>
public static class AppStyles
{
public static ResourceDictionary Create()
{
var styles = new ResourceDictionary();
void Class<T>(string name, BindableProperty property, object value)
where T : BindableObject
{
var style = new Style(typeof(T)) { Class = name, ApplyToDerivedTypes = true };
style.Setters.Add(new Setter { Property = property, Value = value });
styles.Add(style);
}
Class<Label>("field-label", Label.FontSizeProperty, 18d);
Class<Label>("date-field-label", Label.FontSizeProperty, 18d);
Class<Label>("quantity-input-div-label", Label.FontSizeProperty, 18d);
Class<Label>("field-description", Label.FontSizeProperty, 15d);
Class<Label>("field-error", Label.FontAttributesProperty, FontAttributes.Bold);
Class<Label>("error-summary-title", Label.FontSizeProperty, 22d);
Class<Label>("error-summary-title", Label.FontAttributesProperty, FontAttributes.Bold);
Class<Label>("repeatable-fieldset-legend", Label.FontAttributesProperty, FontAttributes.Bold);
Class<Label>("step-list-item-status", Label.FontSizeProperty, 14d);
Class<HorizontalStackLayout>("step-list-item-in-progress", HorizontalStackLayout.BackgroundColorProperty, Colors.Transparent);
return styles;
}
} MauiProgram.cs
using LilyDesignSystem.Maui.Themes;
namespace PreOperativeAssessment;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>();
return builder.Build();
}
}
public class App : Application
{
public App()
{
// The app draws Lily's light theme only, so the system draws its own parts (the status bar) for light too, even in
// dark mode.
UserAppTheme = AppTheme.Light;
// The light theme's tokens, for {DynamicResource lily-color-…}, and the app's styles for Lily's class hooks.
LilyTheme.Apply(Resources, LilyTokens.Light);
Resources.MergedDictionaries.Add(AppStyles.Create());
}
protected override Window CreateWindow(IActivationState? activationState) =>
new(new QuestionnairePage()) { Title = Words.Title };
} Check your work: run dotnet build -t:Run -f net11.0-ios (or net11.0-android). Press Continue without answering: the error summary lists
five problems, and each one takes you to its question. Type 31 2 1990: the date is not
accepted. Answer Yes to medicines and add two, then close the app and open it again:
your answers are still there.
What this does not do yet
- Send sends nowhere: a real app sends the answers to the clinic's service, over a secure connection, and keeps nothing on the phone once it has.
- The clinic's view, with what to look at first, is in the web tutorial.
- It has no test that drives the screens; the rules have theirs, and the Swift and Kotlin versions show a UI test with the platform's accessibility checks.
- It has one language. The words are in one place, so adding another touches no page.
Next steps
- Swift version: the same questionnaire on iPhone, with SwiftUI.
- Kotlin version: the same questionnaire on Android, with Jetpack Compose.
- Book an appointment in .NET MAUI: a phone screen with a top bar and a tab bar.