XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
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.Admin.Utilities;

namespace XFEWarframe.Admin.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<object> NavigationParameters { get; } =
        ServiceManager.GetService<IAutoNavigationParameterService<object>>();
    public IAsyncRelayCommand<object?> LoadCommand { get; }
    protected CancellationToken Lifetime => App.Lifetime;
    protected INavigationViewService Navigation => ServiceManager.GetGlobalService<INavigationViewService>()!;
    protected IMessageService Messages => ServiceManager.GetGlobalService<IMessageService>()!;

    protected ViewModelBase()
    {
        LoadCommand = new AsyncRelayCommand<object?>(parameter => RunAsync(() => LoadAsync(parameter)));
        NavigationParameters.ParameterChange += (_, parameter) => LoadCommand.Execute(parameter);
    }

    protected virtual Task LoadAsync(object? parameter) => Task.CompletedTask;

    protected async Task RunAsync(Func<Task> action, bool overlay = false)
    {
        if (IsBusy || Lifetime.IsCancellationRequested) return;
        IsBusy = true;
        LastError = null;
        var loading = ServiceManager.GetGlobalService<ILoadingService>();
        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);
}