Last active
March 3, 2016 21:36
-
-
Save ginomessmer/5070055e8db57ec67587 to your computer and use it in GitHub Desktop.
Simple implementation of ICommand, usable in ViewModels as Commands
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.Windows.Input; | |
// TODO: Namespace | |
/// <summary> | |
/// Simple implementation of ICommand, usable in ViewModels as Commands. | |
/// Acts like a common RelayCommand. | |
/// Example written in C# 6. | |
/// </summary> | |
/// <example> | |
/// Default approach: public BridgeCommand YourCommand => new BridgeCommand(action => { this.DoSomething(); }); | |
/// XAML: <Button Content="Execute" Command="{Binding YourCommand}"/> | |
/// | |
/// CommandParameter: public BridgeCommand YourCommand => new BridgeCommand(this.DoSomething); | |
/// Command Method: void DoSomething(object obj = null) | |
/// </example> | |
public class BridgeCommand : ICommand | |
{ | |
private Action<object> execute; | |
private Predicate<object> canExecute; | |
public BridgeCommand(Action<object> execute) | |
: this(execute, DefaultCanExecute) | |
{ | |
} | |
public BridgeCommand(Action<object> execute, Predicate<object> canExecute) | |
{ | |
if (execute == null) | |
throw new ArgumentNullException("execute Action<> parameter is null"); | |
this.execute = execute; | |
this.canExecute = canExecute; | |
} | |
public bool CanExecute(object parameter) => canExecute == null || canExecute.Invoke(parameter); | |
public event EventHandler CanExecuteChanged | |
{ | |
add | |
{ | |
if (canExecute != null) | |
CommandManager.RequerySuggested += value; | |
} | |
remove | |
{ | |
if (canExecute != null) | |
CommandManager.RequerySuggested -= value; | |
} | |
} | |
public void Execute(object parameter) => execute.Invoke(parameter); | |
private static bool DefaultCanExecute(object parameter) => true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment