【问题标题】:AsyncCommand in .NET MAUI.NET MAUI 中的 AsyncCommand
【发布时间】:2023-01-31 06:23:31
【问题描述】:

我似乎无法在 .NET MAUI 或 .NET MAUI Community Toolkit 中找到 AsyncCommand。知道我能找到什么包/命名空间吗?

【问题讨论】:

    标签: xamarin xamarin.forms .net-maui xamarin-community-toolkit maui-community-toolkit


    【解决方案1】:

    https://devblogs.microsoft.com/dotnet/introducing-the-net-maui-community-toolkit-preview/#what-to-expect-in-net-maui-toolkit

    .NET MAUI 工具包将不包含 Xamarin 的 MVVM 功能 社区工具包,例如 AsyncCommand。展望未来,我们将添加 所有 MVVM 特定的功能到一个新的 NuGet 包, CommunityToolkit.MVVM。

    【讨论】:

    • 我想将它放在一个单独的包中是个更好的主意。谢谢!
    • 看起来他们放弃了AsyncCommand,转而支持AsyncRelayCommand
    • 将它放在那里并最终直接作为 .NET 的一部分更有意义 :)
    【解决方案2】:

    即使它已被标记为已解决,有人可能会从这个解决方案中获益,该解决方案确实写得非常好 John Thiriet。我暗示了它,而且效果很好。 https://johnthiriet.com/mvvm-going-async-with-async-command/

    public interface IAsyncCommand<T> : ICommand
    {
        Task ExecuteAsync(T parameter);
        bool CanExecute(T parameter);
    }
    
    public class AsyncCommand<T> : IAsyncCommand<T>
    {
        public event EventHandler CanExecuteChanged;
    
        private bool _isExecuting;
        private readonly Func<T, Task> _execute;
        private readonly Func<T, bool> _canExecute;
        private readonly IErrorHandler _errorHandler;
    
        public AsyncCommand(Func<T, Task> execute, Func<T, bool> canExecute = null, IErrorHandler errorHandler = null)
        {
            _execute = execute;
            _canExecute = canExecute;
            _errorHandler = errorHandler;
        }
    
        public bool CanExecute(T parameter)
        {
            return !_isExecuting && (_canExecute?.Invoke(parameter) ?? true);
        }
    
        public async Task ExecuteAsync(T parameter)
        {
            if (CanExecute(parameter))
            {
                try
                {
                    _isExecuting = true;
                    await _execute(parameter);
                }
                finally
                {
                    _isExecuting = false;
                }
            }
    
            RaiseCanExecuteChanged();
        }
    
        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    
    //#region Explicit implementations
        bool ICommand.CanExecute(object parameter)
        {
            return CanExecute((T)parameter);
        }
    
        void ICommand.Execute(object parameter)
        {
            ExecuteAsync((T)parameter).FireAndForgetSafeAsync(_errorHandler);
        }
    //#endregion
    }
    

    【讨论】:

      【解决方案3】:

      安装 CommunityToolkitMVVM 8.0.0

      [RelayCommand]
      async Task your_method (){...}
      

      【讨论】:

        猜你喜欢
        • 2022-12-23
        • 2022-12-24
        • 2022-12-27
        • 2023-01-12
        • 2022-12-17
        • 2022-10-13
        • 2021-12-15
        • 2022-11-02
        • 2023-01-25
        相关资源
        最近更新 更多