Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 42 ยท Testing and Publishing

Debugging and Diagnostics

Debug .NET MAUI apps with breakpoints, Hot Reload, binding error logs, ILogger, crash reports and UI tests; includes runnable logging and exception-handling stand-ins in C#.

Apps run on devices you cannot see into: a phone in a customer's pocket, an emulator with a different locale. Good debugging habits shorten the loop between "something is wrong" and "I know why". This lesson covers the dev tools, the typical MAUI problems (bindings that silently do nothing, lifecycle surprises), structured logging, crash handling and an overview of UI testing.

The IDE tools, device logs and test frameworks are described read-only. The runnable stand-ins show a logging pipeline and a global exception handler in plain C#.

The inner loop: run, change, see

  • Breakpoints and the debugger. Run in Debug configuration, click the gutter in Visual Studio or VS Code, and inspect variables. Conditional breakpoints (i == 42) and logpoints (print without stopping) help in loops.
  • XAML Hot Reload. Edit XAML while the app runs and the page updates, keeping state. Great for tuning layout, colors and margins.
  • .NET Hot Reload. Many C# edits apply to the running app too. Changes to type shapes (new fields, new constructor parameters) or to MauiProgram may need a restart.
  • Live Visual Tree and Live Property Explorer. Visual Studio shows the actual element tree on the device and the value of each property. It answers questions such as "why is this label invisible: is its HeightRequest 0 or is its parent clipping it?"
  • XAML binding diagnostics. Binding failures are logged, not thrown.

Binding errors

The most common MAUI bug is a binding that does nothing: a typo in the path, a missing BindingContext, a property with no setter or no change notification. In Debug, MAUI writes a line to the output window:

TEXT
[0:] Binding: 'Titel' property not found on 'MyApp.ViewModels.MainViewModel', target property: 'Microsoft.Maui.Controls.Label.Text'

Read the log before anything else when a control stays empty. Typical causes:

Symptom Likely cause
Label never shows the text Wrong property name or BindingContext not set
Value shows once but never updates View model does not raise PropertyChanged
Changing the view model list does not update CollectionView Using List<T> instead of ObservableCollection<T>
Command button does nothing The command property is null, or the CanExecute returns false
Works in code, not from a background thread UI updates must run on the main thread

Compiled bindings (x:DataType in XAML) turn many of those mistakes into compile-time errors, so use them:

XML
<ContentPage xmlns:vm="clr-namespace:MyApp.ViewModels"
             x:DataType="vm:MainViewModel">
    <Label Text="{Binding Title}" />   <!-- a typo here fails the build -->
</ContentPage>

They are also faster than reflection-based bindings, and they are required for trimming and Native AOT.

Threads

UI controls may only be touched from the main thread. Awaiting a task in an event handler returns to the main thread automatically, but code in Task.Run, timers and platform callbacks may not:

C#
await Task.Run(() => HeavyWork());                // background
MainThread.BeginInvokeOnMainThread(() => label.Text = "Done");

bool onUi = MainThread.IsMainThread;
string text = await MainThread.InvokeOnMainThreadAsync(() => entry.Text);

Symptoms of a wrong-thread update are a crash with "only the original thread that created a view can touch its views" (Android) or a silent no-op (iOS, depending on the control).

Structured logging with ILogger

Console.WriteLine is not logging. MAUI uses the same Microsoft.Extensions.Logging as ASP.NET Core:

C#
// MauiProgram.cs
#if DEBUG
builder.Logging.AddDebug();
#endif
C#
public class SyncService(ILogger<SyncService> logger)
{
    public async Task RunAsync()
    {
        logger.LogInformation("Sync started for user {UserId}", 42);
        try
        {
            await DoWorkAsync();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Sync failed after {Attempts} attempts", 3);
        }
    }
}

Levels from low to high are Trace, Debug, Information, Warning, Error and Critical. A provider decides the minimum level it prints. Message templates () keep the values as data, not just text, which matters when you ship logs to a service. On Android, AddDebug() goes to Logcat, on iOS to the unified log, and on Windows to the debugger output. Never log passwords, tokens or personal data.

C# Stand-in: a logger with levels and providers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Catching crashes

Unhandled exceptions end the app. Register handlers early so you can record the crash (you cannot usually recover from it):

C#
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
    Log((Exception)e.ExceptionObject, "AppDomain");

TaskScheduler.UnobservedTaskException += (s, e) =>
{
    Log(e.Exception, "UnobservedTask");
    e.SetObserved();
};

Platform specific hooks also exist (Android AndroidEnvironment.UnhandledExceptionRaiser). For real apps use a crash reporting service (App Center is retired; Sentry, Firebase Crashlytics and Raygun have MAUI SDKs) that uploads reports, with symbol files so stack traces show method names.

async void event handlers are the classic way to crash an app, because an exception in them cannot be awaited by the caller. Wrap their body in try/catch, or call an async Task method and handle the failure there:

C# Stand-in: a safe wrapper for async event handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Finding platform problems

  • Android: adb logcat or the Logcat window shows everything, including native crashes. Filter by your package name or the tag DOTNET.
  • iOS: the Xcode Devices window or the Console app shows device logs. A debug build that works but a release build that crashes often means the linker trimmed something; check TrimMode and [DynamicDependency]/[Preserve] attributes.
  • Windows: the Visual Studio output window and the Event Viewer.
  • "Works in Debug, fails in Release": trimming, AOT and missing resources. Test the Release build on a real device before every release.

UI tests

Unit tests cover logic. UI tests drive the real app:

  • Appium with the appium-dotnet-client NUnit project: it launches the app and finds elements by their AutomationId. This is the approach recommended for MAUI.
  • Give every control a stable id: <Button AutomationId="SaveButton" />.
  • Keep UI tests few and slow, unit tests many and fast: the test pyramid.
C#
[Test]
public void SavingShowsConfirmation()
{
    _app.FindElement(MobileBy.AccessibilityId("NameEntry")).SendKeys("Ana");
    _app.FindElement(MobileBy.AccessibilityId("SaveButton")).Click();
    Assert.That(_app.FindElement(MobileBy.AccessibilityId("StatusLabel")).Text, Is.EqualTo("Saved"));
}

A debugging checklist

  1. Read the output window for binding errors and exceptions.
  2. Check BindingContext and x:DataType.
  3. Use the Live Visual Tree to inspect sizes and visibility.
  4. Reproduce on another platform: is it MAUI or the native layer?
  5. Search the log for the first error, not the last; later ones are usually fallout.
  6. Reduce the page to the smallest code that still fails.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when a binding path contains a typo?

    Reflection-based bindings fail silently with a log line. Compiled bindings (x:DataType) catch many typos at build time.
  2. 2. Why use ObservableCollection<T> for a CollectionView ItemsSource?

    List<T> does not notify the UI about adds and removes; ObservableCollection<T> does.
  3. 3. Why is async void dangerous?

    Because there is no Task to observe, an unhandled exception goes straight to the unhandled-exception path. Wrap the body in try/catch.
  4. 4. How do UI tests with Appium find a control reliably?

    AutomationId gives each control a stable identifier that does not change with layout or language.

Summary

  • Use breakpoints, Hot Reload and the Live Visual Tree for the inner loop.
  • Binding problems are logged, not thrown: read the output and use x:DataType.
  • Touch UI only on the main thread; use ILogger with levels and never log secrets.
  • Record crashes with global handlers or a crash service; avoid unguarded async void.
  • UI tests with Appium use AutomationId; keep them few, and test Release builds on real devices.

Next: Performance and Startup