CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets My Favorites Favorites Web Code Search Snippets Search
Sign inor Register
Language: C#

Typed DelegateCommand for WinRT

671 Views   
public class DelegateCommand<T> : System.Windows.Input.ICommand
{
    private readonly Action<T> m_Execute;
    private readonly Func<T, bool> m_CanExecute;
    public event EventHandler CanExecuteChanged;
 
    public DelegateCommand(Action<T> execute)
        : this(execute, (x) => true) { /* empty */ }
 
    public DelegateCommand(Action<T> execute, Func<T, bool> canexecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        m_Execute = execute;
        m_CanExecute = canexecute;
    }
 
    [DebuggerStepThrough]
    public bool CanExecute(object p)
    {
        try
        {
            var _Value = (T)Convert.ChangeType(p, typeof(T));
            return m_CanExecute == null ? true : m_CanExecute(_Value);
        }
        catch
        {
            Debugger.Break();
            return false;
        }
    }
 
    public void Execute(object p)
    {
        if (CanExecute(p))
            try
            {
                var _Value = (T)Convert.ChangeType(p, typeof(T));
                m_Execute(_Value);
            }
            catch { Debugger.Break(); }
    }
 
    public void RaiseCanExecuteChanged()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, EventArgs.Empty);
    }
}
by Jerry Nixon
  October 06, 2012 @ 10:32pm
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies