using System.Linq; using System.Threading.Tasks; using Avalonia.Controls; using Avalonia.Controls.Platform; namespace Avalonia.Dialogs { public static class ManagedFileDialogExtensions { private class ManagedSystemDialogImpl : ISystemDialogImpl where T : Window, new() { async Task Show(SystemDialog d, Window parent, ManagedFileDialogOptions options = null) { var model = new ManagedFileChooserViewModel((FileSystemDialog)d, options ?? new ManagedFileDialogOptions()); var dialog = new T { Content = new ManagedFileChooser(), Title = d.Title, DataContext = model }; dialog.Closed += delegate { model.Cancel(); }; string[] result = null; model.CompleteRequested += items => { result = items; dialog.Close(); }; model.CancelRequested += dialog.Close; await dialog.ShowDialog(parent); return result; } public async Task ShowFileDialogAsync(FileDialog dialog, Window parent) { return await Show(dialog, parent); } public async Task ShowFolderDialogAsync(OpenFolderDialog dialog, Window parent) { return (await Show(dialog, parent))?.FirstOrDefault(); } public async Task ShowFileDialogAsync(FileDialog dialog, Window parent, ManagedFileDialogOptions options) { return await Show(dialog, parent, options); } } public static TAppBuilder UseManagedSystemDialogs(this TAppBuilder builder) where TAppBuilder : AppBuilderBase, new() { builder.AfterSetup(_ => AvaloniaLocator.CurrentMutable.Bind().ToSingleton>()); return builder; } public static TAppBuilder UseManagedSystemDialogs(this TAppBuilder builder) where TAppBuilder : AppBuilderBase, new() where TWindow : Window, new() { builder.AfterSetup(_ => AvaloniaLocator.CurrentMutable.Bind().ToSingleton>()); return builder; } public static Task ShowManagedAsync(this OpenFileDialog dialog, Window parent, ManagedFileDialogOptions options = null) => ShowManagedAsync(dialog, parent, options); public static Task ShowManagedAsync(this OpenFileDialog dialog, Window parent, ManagedFileDialogOptions options = null) where TWindow : Window, new() { return new ManagedSystemDialogImpl().ShowFileDialogAsync(dialog, parent, options); } } }