Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created September 17, 2018 09:31
Show Gist options
  • Save fearofcode/2ff7c25a7460214a662edbff2800192a to your computer and use it in GitHub Desktop.
Save fearofcode/2ff7c25a7460214a662edbff2800192a to your computer and use it in GitHub Desktop.
MVVM toolkit in a screenful of code
namespace MVVMToolkit
{
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class RelayCommand : ICommand
{
readonly Action<object> action;
readonly Predicate<object> canExecute;
public RelayCommand(Action<object> execute) : this(execute, null) { }
public RelayCommand(Action<object> action, Predicate<object> canExecute)
{
this.action = action ?? throw new ArgumentNullException("execute");
this.canExecute = canExecute;
}
public bool CanExecute(object parameters)
{
return canExecute == null ? true : canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
action(parameters);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment