Created
December 8, 2017 09:18
-
-
Save AlekseyGett/9007f27231681ba4340ce1741b6d2fc6 to your computer and use it in GitHub Desktop.
Implementation of ICommand interface
This file contains hidden or 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.Windows.Input; | |
| namespace MVVM | |
| { | |
| public class ActionCommand : ICommand | |
| { | |
| private Action<object> action; | |
| private Predicate<object> predicate; | |
| public ActionCommand(Action<object> action) : this(action, null) | |
| { } | |
| public ActionCommand(Action<object> action, Predicate<object> predicate) | |
| { | |
| this.action = action ?? throw new ArgumentNullException(nameof(action)); | |
| this.predicate = predicate; | |
| } | |
| #region ICommand members: | |
| public event EventHandler CanExecuteChanged | |
| { | |
| add { CommandManager.RequerySuggested += value; } | |
| remove { CommandManager.RequerySuggested -= value; } | |
| } | |
| public bool CanExecute(object parameter) => | |
| predicate == null || predicate(parameter); | |
| public void Execute() => | |
| Execute(null); | |
| public void Execute(object parameter) => | |
| action(parameter); | |
| #endregion | |
| } | |
| } |
This file contains hidden or 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 MVVM | |
| { | |
| public class ActionCommandAsync : ICommand | |
| { | |
| private Func<object, Task> action; | |
| private Predicate<object> predicate; | |
| private bool executing = false; | |
| public ActionCommandAsync(Func<object, Task> action) : this(action, null) | |
| { } | |
| public ActionCommandAsync(Func<object, Task> action, Predicate<object> predicate) | |
| { | |
| this.action = action ?? throw new ArgumentNullException(nameof(action)); | |
| this.predicate = predicate; | |
| } | |
| #region ICommand members: | |
| public event EventHandler CanExecuteChanged | |
| { | |
| add { CommandManager.RequerySuggested += value; } | |
| remove { CommandManager.RequerySuggested -= value; } | |
| } | |
| public bool CanExecute(object parameter) => | |
| !executing && (predicate == null || predicate(parameter)); | |
| public void Execute() => | |
| Execute(null); | |
| public async void Execute(object parameter) | |
| { | |
| var task = action(parameter); | |
| if (task != null) | |
| { | |
| executing = true; | |
| await task; | |
| executing = false; | |
| } | |
| } | |
| #endregion | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment