using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.UI.Xaml.Controls; using XFEExtension.NetCore.WinUIHelper.Interface.Services; using XFEExtension.NetCore.WinUIHelper.Utilities; using XFEWarframe.Player.Utilities; namespace XFEWarframe.Player.ViewModels; public abstract partial class ViewModelBase : ObservableObject { [ObservableProperty] [NotifyPropertyChangedFor(nameof(IsIdle))] public partial bool IsBusy { get; set; } public bool IsIdle => !IsBusy; [ObservableProperty] public partial string? LastError { get; set; } public IAutoNavigationParameterService NavigationParameters { get; } = ServiceManager.GetService>(); public IAsyncRelayCommand LoadCommand { get; } protected CancellationToken Lifetime => App.Lifetime; protected INavigationViewService Navigation => ServiceManager.GetGlobalService()!; protected IMessageService Messages => ServiceManager.GetGlobalService()!; protected ViewModelBase() { LoadCommand = new AsyncRelayCommand(parameter => RunAsync(() => LoadAsync(parameter))); NavigationParameters.ParameterChange += (_, parameter) => LoadCommand.Execute(parameter); } protected virtual Task LoadAsync(object? parameter) => Task.CompletedTask; protected async Task RunAsync(Func action, bool overlay = false) { if (IsBusy || Lifetime.IsCancellationRequested) return; IsBusy = true; LastError = null; var loading = ServiceManager.GetGlobalService(); if (overlay) loading?.StartLoading("正在处理…"); try { await action(); } catch (OperationCanceledException) { } catch (Exception ex) { AppPath.LogException(ex); LastError = ex.Message; if (!Lifetime.IsCancellationRequested) Messages.ShowMessage(ex.Message, "操作未完成", InfoBarSeverity.Error); } finally { if (overlay) loading?.StopLoading(); IsBusy = false; } } protected void Notify(string message) => Messages.ShowMessage(message, "已完成", InfoBarSeverity.Success); }