Skip to content

Latest commit

 

History

History
162 lines (101 loc) · 7.9 KB

dialogs.md

File metadata and controls

162 lines (101 loc) · 7.9 KB

IDialogService Members

Inject IDialogService into the constructor when the ViewModel needs to open child dialogs.

owner is the ViewModel whose view will be the dialog parent; usually this.

Dialogs and Pages

void Show(owner, viewModel): Opens a non-modal view.

bool? ShowDialogAsync(owner, viewModel): Shows a dialog, waits for closure and returns IModalDialogViewModel.DialogResult. The ViewModel itself can return more data.

Note: this can either show as child window or single-page navigation depending on platform.

In navigation mode, awaiting ShowDialogAsync throws OperationCanceledException if the dialog owner or navigation host closes while the dialog is pending.

See ViewModels to design the child View Models.

Custom Dialog Extension

The recommended way of accessing your dialogs is to create a DialogExtensions class containing strongly-typed access to all your dialogs.

public static class DialogExtensions
{
    public static async Task<PresetItem?> ShowLoadPresetViewAsync(this IDialogService dialog, INotifyPropertyChanged ownerViewModel)
    {
        var vm = dialog.CreateViewModel<SelectPresetViewModel>();
        vm.Load();
        var result = await dialog.ShowDialogAsync(ownerViewModel, vm).ConfigureAwait(true);
        return result == true ? vm.SelectedItem : null;
    }
}

To make your code testable, use IDialogService.CreateViewModel<T> to create your dialog view models. It will call viewModelFactory function that you set in DialogService constructor.

Then the usage is super sexy! (a long way from ReactiveUI Interactions...)

var preset = await dialogService.ShowLoadPresetViewAsync(this);

Framework dialogs

The picker methods take an owner and optional picker settings and return a Task.

IDialogStorageFile? ShowOpenFileDialogAsync: Shows a system open file dialog.

IReadOnlyList<IDialogStorageFile> ShowOpenFilesDialogAsync: Shows a system open file dialog. Set settings.AllowMultiple to allow selection.

IDialogStorageFile? ShowSaveFileDialogAsync: Shows a system save file dialog.

IDialogStorageFolder? ShowOpenFolderDialogAsync`: Shows a system open folder dialog.

IReadOnlyList<IDialogStorageFolder> ShowOpenFoldersDialogAsync: Shows a system open folder dialog. Set settings.AllowMultiple = true to request multiple selection where supported.

The dialog factory selects an implementation by settings type.

Cross-platform file access

A browser file or Android content URI may have no local path, so you get a file stream instead. LocalPath returns the local storage path on desktop, or null if the provider doesn't expose it.

Use OpenWriteAsync() on a file returned by the save picker. Write the complete new contents and dispose the stream to finish writing. Dispose each returned storage item after use. For Uno, read its doc.

using var file = await dialogs.ShowOpenFileDialogAsync(this);
if (file is null) { return; }
using var stream = await file.OpenReadAsync();
using var reader = new StreamReader(stream);
var text = await reader.ReadToEndAsync();

IDialogStorageItem

Inherited by both File and Folders. The storage provider controls which operations are available. Dispose each item returned by a picker, lookup, or enumeration when you're done with it.

string Name: The display name.

Uri Path: The provider URI.

string? LocalPath: The local file path, or null if unavailable.

DesktopDialogStorageItemProperties GetBasicPropertiesAsync(): Size and timestamps when available.

IDialogStorageFolder? GetParentAsync(): The parent folder, or null if unavailable.

Task DeleteAsync(): Deletes the item.

IDialogStorageItem? MoveAsync(destination): Moves the item and returns the moved item, or null if the provider can't perform the move.

IDialogStorageFile

Stream OpenReadAsync(): Opens the file for reading.

OpenWriteAsync() opens a stream to replace the file contents.

IDialogStorageFolder

IAsyncEnumerable<IDialogStorageItem> GetItemsAsync(): Enumerates files and subfolders.

IDialogStorageFile? GetFileAsync(name): Returns the named file, or null if not found.

IDialogStorageFolder? GetFolderAsync(name): Returns the named subfolder, or null if not found.

IDialogStorageFile? CreateFileAsync(name): Creates and returns a file, or null if the provider can't create it. For DesktopDialogStorageFolder, this truncates an existing file immediately and throws DirectoryNotFoundException if the parent directory is missing. Use GetFileAsync(name) to open an existing file without changing its contents.

IDialogStorageFolder? CreateFolderAsync(name): Creates and returns a subfolder, or null if the provider can't create it.

For a file path you already have on desktop, construct a DesktopDialogStorageFile. Use IDesktopDialogStorageFactory to substitute storage in tests.

File Filters

There's a slight complication with dialog file filters: Windows, Android, MacOS and Browser expect completely different file type definitions, and this discrepancy is handled differently in each framework. We decided to adopt Uno's design and apply it to all platforms.

Define filters by extension in FileDialogSettings.Filters. Set SuggestedFileType to an entry in Filters. After acceptance, SelectedFileType contains the choice if the picker reports it.

var textFiles = new FileFilter("Text files", "txt");
var settings = new OpenFileDialogSettings
{
    Filters = [textFiles, new FileFilter("All files", "*")],
    SuggestedFileType = textFiles
};
using var file = await dialogs.ShowOpenFileDialogAsync(this, settings);

For mobile devices, extensions are auto-translated to their MIME or Apple type identifiers using the default registrations in this file. Declare custom types on DialogFactory in the app's startup.

var factory = new DialogFactory();
factory.RegisterFileTypes(new FileTypeRegistration(
    "vpy", mimeType: OperatingSystem.IsAndroid() ? "application/octet-stream" : "text/x-vapoursynth",
    appleType: "org.vapoursynth-script"));
var dialogs = new DialogService(new DialogManager(dialogFactory: factory));

Custom dialog factories

  1. For a new dialog, derive its settings from DialogSettingsBase. To override a built-in dialog, use its existing settings type.
  2. Derive from the platform’s dialog factory or factory base. Override ShowDialogAsync to handle your settings type and forward other requests to base.ShowDialogAsync. For WPF sync calls, also override ShowDialog.
  3. Give the custom factory the platform factory as its fallback and pass the custom factory to DialogManager.
  4. For a new dialog, expose a typed IDialogService extension that calls service.DialogManager.ShowFrameworkDialogAsync.

When handling OpenFolderDialogSettings, return an IReadOnlyList<IDialogStorageFolder> even for a single-folder request. Return an empty list on cancellation.

IReadOnlyList<IDialogStorageFolder> folders = selectedFolder is null ? [] : [selectedFolder];
return folders;

Message boxes

bool? ShowMessageBoxAsync(owner, text, title, MessageBoxButton, MessageBoxImage, defaultResult): Shows a message box with the supplied text and options.

bool? ShowMessageBoxAsync(owner, MessageBoxSettings?): Shows a message box with supplied settings.

Returns true for OK or Yes, false for No, and null for Cancel.

Multiple MessageBox implementations are available, and you can implement your own on the DialogFactory. Avalonia doesn't come with any MessageBox implementations built-in and you must register one of the implementations at startup.

Asynchronous framework dialogs and message boxes queue by default. Set IDialogManager.AllowConcurrentDialogs to allow overlap where the provider supports it.