Advertisement
Deozaan

RelayCommand.cs (WPF MVVM)

Sep 29th, 2020 (edited)
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Windows.Input;
  3.  
  4. public class RelayCommand<T> : ICommand {
  5.     private readonly Action<T> _execute = null;
  6.     private readonly Func<T, bool> _canExecute = null;
  7.  
  8.     public RelayCommand(Action<T> execute, Func<T, bool> canExecute = null) {
  9.         _execute = execute ?? throw new ArgumentNullException(nameof(execute));
  10.         _canExecute = canExecute ?? (_ => true);
  11.     }
  12.  
  13.     public event EventHandler CanExecuteChanged {
  14.         add => CommandManager.RequerySuggested += value;
  15.         remove => CommandManager.RequerySuggested -= value;
  16.     }
  17.  
  18.     public bool CanExecute(object parameter) => _canExecute((T)parameter);
  19.  
  20.     public void Execute(object parameter) => _execute((T)parameter);
  21. }
  22.  
  23. public class RelayCommand : RelayCommand<object> {
  24.     public RelayCommand(Action execute)
  25.         : base(_ => execute()) { }
  26.  
  27.     public RelayCommand(Action execute, Func<bool> canExecute)
  28.         : base(_ => execute(), _ => canExecute()) { }
  29. }
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement