-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActionCommand.cs
71 lines (60 loc) · 1.72 KB
/
ActionCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// ReSharper disable UnusedMemberInSuper.Global
using System;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Sudoku
{
public interface IAsyncCommand<in T> : ICommand
{
Task ExecuteAsync(T parameter);
bool CanExecute(T parameter);
}
public class AsyncCommand<T> : IAsyncCommand<T>
{
private bool _isExecuting;
private readonly Func<T, Task> _execute;
private readonly Func<T, bool> _canExecute;
public AsyncCommand(Func<T, Task> execute, Func<T, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
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;
}
}
}
#region Explicit implementations
bool ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
//Fire and forget
#pragma warning disable 4014
ExecuteAsync((T)parameter);
#pragma warning restore 4014
}
#endregion
}
}