Commands structure
using System;
using System.Windows.Input;
using System.Windows.Markup;
namespace Commands
{
public class RelayCommand : MarkupExtension, ICommand
{
private readonly Func<object, bool> _canExecute;
private readonly Action<object> _execute;
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
if (CanExecute(parameter))
_execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using System.Windows.Markup;
namespace Commands
{
public class DelegateCommand : MarkupExtension, ICommand
{
public IEnumerable<Command> Commands { get; set; }
public DelegateCommand()
{
Commands = new Command[] { };
}
public DelegateCommand(IEnumerable<Command> commands)
{
Commands = commands;
}
public bool CanExecute(object parameter)
{
return Commands != null && Commands.Any();
}
public void Execute(object parameter)
{
if (CanExecute(parameter))
foreach (var command in Commands)
{
var param = command.UseParentParameter ? parameter : command.Parameter;
var action = command.Action;
if (action.CanExecute(param)) action.Execute(param);
}
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
using System;
using System.Windows.Input;
using System.Windows.Markup;
namespace Commands
{
public class Command : MarkupExtension
{
public Command()
{
UseParentParameter = false;
}
public ICommand Action { get; set; }
public object Parameter { get; set; }
public bool UseParentParameter { get; set; }
public static Command CreateCommand(Action<object> executeAction, object parameter = null, Func<object, bool> canExecuteAction = null)
{
Func<object, bool> canExecute = o => true;
if (canExecuteAction != null) canExecute = canExecuteAction.Invoke;
return new Command
{
Action = new RelayCommand(executeAction.Invoke, canExecute),
Parameter = parameter
};
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}