Avalonia Field Guide
About

Module 2 · Lesson 09 of 16

A dialog is a window with a result

ShowDialog<T> blocks the caller until the child closes and hands back a value. Files go through IStorageProvider, never a path you guessed.

30 minHeadless-tested

A dialog is not a second application. It is a Window with a lifetime measured in seconds and a single value to return.

Screenshot of the dialogs lesson sample
The lesson's sample, rendered headlessly at 1280×800. Light and dark are both captured.

The mechanism

var confirmed = await new ConfirmDialog(title, message).ShowDialog<bool>(owner);

ShowDialog<T> shows the child, disables the owner, and completes when the child closes. The value comes from Close(result):

src/CourseApp/Lessons/14_Dialogs/ConfirmDialog.axaml.cs
using Avalonia.Controls;
using Avalonia.Interactivity;

namespace CourseApp.Lessons.Dialogs;

/// <summary>A dialog is a Window that closes with a result. ShowDialog&lt;bool&gt; is the API.</summary>
public partial class ConfirmDialog : Window
{
    public ConfirmDialog() : this("Delete project?", "This cannot be undone.") { }

    public ConfirmDialog(string title, string message)
    {
        InitializeComponent();
        TitleText.Text = title;
        MessageText.Text = message;
    }

    void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);

    void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
}

Close() with no argument returns default(T) — false for this dialog. That is a safe default for a delete confirmation, and a dangerous one for "save changes?". Decide deliberately, and test the cancel path.

Keep the view model out of the window business

src/CourseApp/Lessons/14_Dialogs/DialogsViewModel.cs
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace CourseApp.Lessons.Dialogs;

public partial class DialogsViewModel : ObservableObject
{
    readonly Func<string, string, Task<bool>> _confirm;
    readonly Func<Task<string?>> _pick;

    public DialogsViewModel(
        Func<string, string, Task<bool>>? confirm = null,
        Func<Task<string?>>? pick = null)
    {
        // Seams: production wires real windows and IStorageProvider; tests pass fakes.
        _confirm = confirm ?? ((_, _) => Task.FromResult(false));
        _pick = pick ?? (() => Task.FromResult<string?>(null));
    }

    [ObservableProperty]
    private string _status = "No dialog opened yet.";

    [ObservableProperty]
    private string _file = "No file selected.";

    [RelayCommand]
    private async Task DeleteAsync()
    {
        var confirmed = await _confirm("Delete project?", "This cannot be undone.");
        Status = confirmed ? "Deleted. The dialog returned true." : "Cancelled. The dialog returned false.";
    }

    [RelayCommand]
    private async Task PickAsync()
    {
        var path = await _pick();
        File = path is null ? "Picker cancelled." : path;
    }
}

The view model takes two delegates: one that shows a confirmation, one that picks a file. Production supplies real implementations; the verifier supplies fakes. This is the same seam as the async lesson, applied to the two things that are impossible to test through a real dialog: modality and a native file chooser.

src/CourseApp/Lessons/14_Dialogs/DialogsView.axaml.cs
using Avalonia.Controls;
using Avalonia.Platform.Storage;

namespace CourseApp.Lessons.Dialogs;

public partial class DialogsView : UserControl
{
    public DialogsView()
    {
        InitializeComponent();
        DataContext = new DialogsViewModel(ShowConfirm, PickFile);
    }

    async Task<bool> ShowConfirm(string title, string message)
    {
        if (TopLevel.GetTopLevel(this) is not Window owner)
            return false;

        return await new ConfirmDialog(title, message).ShowDialog<bool>(owner);
    }

    async Task<string?> PickFile()
    {
        var top = TopLevel.GetTopLevel(this);
        if (top is null)
            return null;

        var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
        {
            Title = "Choose a file",
            AllowMultiple = false,
        });

        return files.Count > 0 ? files[0].Path.LocalPath : null;
    }
}

Files are not paths

IStorageProvider lives on the TopLevel. OpenFilePickerAsync returns IStorageItem values, and Path.LocalPath is only meaningful on desktop — a sandboxed app (Flatpak, macOS) may not have permission to read that path directly. For those, open the item's stream instead of re-opening the path later.

var files = await top.StorageProvider.OpenFilePickerAsync(options);
await using var stream = await files[0].OpenReadAsync();

Save dialogs are the mirror image: SaveFilePickerAsync, then write to the returned item. Never construct ~/Documents/... yourself.

Try it

  1. Add a "Save as…" command using SaveFilePickerAsync and write a small text file.
  2. Ask for confirmation before overwriting an existing file.
  3. Add a third button to ConfirmDialog ("Keep both") and change the result type to an enum. The compiler will point at every place that assumed bool.

Next: tokens, scopes, and two themes.

Files this lesson draws from

  • src/CourseApp/Lessons/14_Dialogs/ConfirmDialog.axaml.cs
  • src/CourseApp/Lessons/14_Dialogs/DialogsViewModel.cs
  • src/CourseApp/Lessons/14_Dialogs/DialogsView.axaml.cs

VerifiedThe verifier injects a confirm that returns true and a picker that returns a path, runs both commands, and asserts the results reached the view model.

Back to top