Files
PLib/src/PLib.Desktop/App.axaml.cs
T

56 lines
1.8 KiB
C#

using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PLib.Desktop.Controls;
using PLib.Desktop.Imaging;
using PLib.Desktop.ViewModels;
using PLib.Desktop.Views;
namespace PLib.Desktop;
// Fully qualified: the PLib.Application namespace shadows the Application type in this assembly.
public sealed class App : Avalonia.Application
{
private IHost? _host;
public override void Initialize() => AvaloniaXamlLoader.Load(this);
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
_host = AppHost.Create(desktop.Args ?? []);
_host.Start();
AsyncImage.Loader = _host.Services.GetRequiredService<ThumbnailCache>();
var viewModel = _host.Services.GetRequiredService<MainWindowViewModel>();
desktop.MainWindow = new MainWindow { DataContext = viewModel };
desktop.Exit += OnExit;
// Kick the first load off once the dispatcher is running, so a failure surfaces
// through the view model instead of disappearing into an unobserved task.
Dispatcher.UIThread.Post(
() => viewModel.InitializeCommand.Execute().Subscribe(),
DispatcherPriority.Background);
}
base.OnFrameworkInitializationCompleted();
}
private void OnExit(object? sender, ControlledApplicationLifetimeExitEventArgs e)
{
if (_host is null)
{
return;
}
_host.StopAsync(TimeSpan.FromSeconds(3)).GetAwaiter().GetResult();
_host.Dispose();
_host = null;
}
}