|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace ServiceTreeSample
{
/// <summary>
/// An implementation of the <see cref="ICommand"/> interface
/// that uses a delegate to execute the command.
/// </summary>
/// <typeparam name="TParameter">The type of the parameter.</typeparam>
public class DelegateCommand<TParameter> : ICommand
{
Action<TParameter> execute;
Func<TParameter, bool> canExecute;
/// <summary>
/// Initializes a new instance of the <see cref="DelegateCommand<TParameter>"/> class.
/// </summary>
/// <param name="execute">The execute.</param>
/// <param name="canExecute">The can execute.</param>
public DelegateCommand(Action<TParameter> execute, Func<TParameter, bool> canExecute)
{
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// Initializes a new instance of the <see cref="DelegateCommand<TParameter>"/> class.
/// </summary>
/// <param name="execute">The execute.</param>
public DelegateCommand(Action<TParameter> execute)
: this(execute, null)
{
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged;
/// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
/// <returns>
/// true if this command can be executed; otherwise, false.
/// </returns>
public bool CanExecute(object parameter)
{
if (canExecute == null)
return true;
if (parameter != null && !(parameter is TParameter))
return false;
return canExecute((TParameter)parameter);
}
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public void Execute(object parameter)
{
if (execute != null)
execute((TParameter)parameter);
}
/// <summary>
/// Raises the <see cref="CanExecuteChanged"/> event.
/// </summary>
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
David is a software developer with an obsession for analysis and proper architecture.