-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncRelayCommand.cs
More file actions
49 lines (41 loc) · 1.24 KB
/
Copy pathAsyncRelayCommand.cs
File metadata and controls
49 lines (41 loc) · 1.24 KB
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
using System.Windows.Input;
namespace SimpleMusicPlayer;
public sealed class AsyncRelayCommand : ICommand
{
private readonly Func<object?, Task> _executeAsync;
private readonly Predicate<object?>? _canExecute;
private readonly bool _disableWhileRunning;
private bool _isRunning;
public AsyncRelayCommand(
Func<object?, Task> executeAsync,
Predicate<object?>? canExecute = null,
bool disableWhileRunning = true)
{
_executeAsync = executeAsync;
_canExecute = canExecute;
_disableWhileRunning = disableWhileRunning;
}
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter)
=> (!_disableWhileRunning || !_isRunning) && (_canExecute?.Invoke(parameter) ?? true);
public async void Execute(object? parameter)
{
if (!CanExecute(parameter))
{
return;
}
_isRunning = true;
RaiseCanExecuteChanged();
try
{
await _executeAsync(parameter);
}
finally
{
_isRunning = false;
RaiseCanExecuteChanged();
}
}
public void RaiseCanExecuteChanged()
=> CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}