// --------------------------------------------------------------------------------------------------------------------
//
// Copyright (c) 2014 OxyPlot contributors
//
//
// Represents a delegate command.
//
// --------------------------------------------------------------------------------------------------------------------
namespace WpfExamples
{
using System;
using System.Windows.Input;
///
/// Represents a delegate command.
///
public class DelegateCommand : ICommand
{
///
/// The can execute.
///
private readonly Func canExecute;
///
/// The execute.
///
private readonly Action execute;
///
/// Initializes a new instance of the class.
///
/// The execute.
public DelegateCommand(Action execute)
: this(execute, null)
{
}
///
/// Initializes a new instance of the class.
///
/// The execute.
/// The can execute.
public DelegateCommand(Action execute, Func canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.execute = execute;
this.canExecute = canExecute;
}
///
/// Occurs when changes occur that affect whether or not the command should execute.
///
public event EventHandler CanExecuteChanged
{
add
{
if (this.canExecute != null)
{
CommandManager.RequerySuggested += value;
}
}
remove
{
if (this.canExecute != null)
{
CommandManager.RequerySuggested -= value;
}
}
}
///
/// Defines the method that determines whether the command can execute in its current state.
///
/// Data used by the command. If the command does not require data to be passed, this object can be set to null.
/// true if this command can be executed; otherwise, false.
public bool CanExecute(object parameter)
{
return this.canExecute == null ? true : this.canExecute();
}
///
/// Defines the method to be called when the command is invoked.
///
/// Data used by the command. If the command does not require data to be passed, this object can be set to null.
public void Execute(object parameter)
{
this.execute();
}
///
/// Raises the can execute changed.
///
public void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
}
}