Created
February 18, 2011 11:17
-
-
Save flq/833551 to your computer and use it in GitHub Desktop.
A command that runs on delegates and implements WPF ICommand
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; | |
namespace Something | |
{ | |
public class RelayCommand : ICommand | |
{ | |
private readonly Func<object, bool> _canExecute; | |
private readonly Action<object> _execute; | |
public RelayCommand(Func<object, bool> canExecute, Action<object> execute) | |
{ | |
_canExecute = canExecute; | |
_execute = execute; | |
} | |
public RelayCommand(Action<object> execute) : this(_ => true, execute) { } | |
public RelayCommand(Action execute) : this(_ => true, _ => execute()) { } | |
public RelayCommand(Func<bool> canExecute, Action execute) : this(_ => canExecute(), _ => execute()) { } | |
public void Execute(object parameter) | |
{ | |
_execute(parameter); | |
} | |
public bool CanExecute(object parameter) | |
{ | |
return _canExecute(parameter); | |
} | |
public void RaiseCanExecuteChanged() | |
{ | |
CommandManager.InvalidateRequerySuggested(); | |
} | |
public event EventHandler CanExecuteChanged | |
{ | |
add { CommandManager.RequerySuggested += value; } | |
remove { CommandManager.RequerySuggested -= value; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment