Created
April 25, 2015 13:23
-
-
Save dimitrispaxinos/f051d67a287bb34947a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using System.Windows.Input; | |
namespace AsyncDisablingScopeSample | |
{ | |
public class RelayCommandAsync : ICommand | |
{ | |
#region Fields | |
private readonly Predicate<object> _canExecute; | |
private Func<object, Task> _asyncExecute; | |
#endregion | |
#region Constructors | |
/// <summary> | |
/// Creates a new command that can always execute. | |
/// </summary> | |
/// <param name="asyncExecute">The execution logic.</param> | |
public RelayCommandAsync(Func<object, Task> asyncExecute) | |
: this(asyncExecute, null) | |
{ | |
} | |
/// <summary> | |
/// Creates a new command. | |
/// </summary> | |
/// <param name="asyncExecute">The execution logic.</param> | |
/// <param name="canExecute">The execution status logic.</param> | |
public RelayCommandAsync(Func<object, Task> asyncExecute, Predicate<object> canExecute) | |
{ | |
if (asyncExecute == null) | |
{ | |
throw new ArgumentNullException("_asyncExecute"); | |
} | |
_asyncExecute = asyncExecute; | |
_canExecute = canExecute; | |
} | |
#endregion | |
#region ICommand Members | |
public bool CanExecute(object parameter) | |
{ | |
return _canExecute == null ? true : _canExecute(parameter); | |
} | |
public event EventHandler CanExecuteChanged | |
{ | |
add { CommandManager.RequerySuggested += value; } | |
remove { CommandManager.RequerySuggested -= value; } | |
} | |
public async void Execute(object parameter) | |
{ | |
await ExecuteAsync(parameter); | |
} | |
protected virtual async Task ExecuteAsync(object parameter) | |
{ | |
await _asyncExecute(parameter); | |
} | |
public string ToolTip { get; set; } | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice gist !
Here's my two cents: adding a
InvokeCanExecuteChanged
public void InvokeCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);