Skip to content

Instantly share code, notes, and snippets.

@dimitrispaxinos
Created April 25, 2015 13:23
Show Gist options
  • Save dimitrispaxinos/f051d67a287bb34947a5 to your computer and use it in GitHub Desktop.
Save dimitrispaxinos/f051d67a287bb34947a5 to your computer and use it in GitHub Desktop.
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
}
}
@ArthurAttout
Copy link

Nice gist !
Here's my two cents: adding a InvokeCanExecuteChanged

public void InvokeCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment