Skip to content

Instantly share code, notes, and snippets.

@ginomessmer
Last active March 3, 2016 21:36
Show Gist options
  • Save ginomessmer/5070055e8db57ec67587 to your computer and use it in GitHub Desktop.
Save ginomessmer/5070055e8db57ec67587 to your computer and use it in GitHub Desktop.
Simple implementation of ICommand, usable in ViewModels as Commands
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