/ src / settings-ui / Settings.UI / Helpers / AsyncCommand.cs
AsyncCommand.cs
 1  // Copyright (c) Microsoft Corporation
 2  // The Microsoft Corporation licenses this file to you under the MIT license.
 3  // See the LICENSE file in the project root for more information.
 4  
 5  using System;
 6  using System.Collections.Generic;
 7  using System.Linq;
 8  using System.Text;
 9  using System.Threading.Tasks;
10  using System.Windows.Input;
11  
12  namespace Microsoft.PowerToys.Settings.UI.Helpers
13  {
14      internal sealed partial class AsyncCommand : ICommand
15      {
16          private readonly Func<Task> _execute;
17          private readonly Func<bool> _canExecute;
18  
19          public event EventHandler CanExecuteChanged;
20  
21          public AsyncCommand(Func<Task> execute, Func<bool> canExecute = null)
22          {
23              _execute = execute;
24              _canExecute = canExecute;
25          }
26  
27          public bool CanExecute(object parameter)
28          {
29              return _canExecute == null || _canExecute();
30          }
31  
32          public async void Execute(object parameter)
33          {
34              await _execute();
35          }
36  
37          public void RaiseCanExecuteChanged()
38          {
39              CanExecuteChanged?.Invoke(this, EventArgs.Empty);
40          }
41      }
42  }