Friday, September 12, 2014

WPF Command

Got lost on the new Command here:

public ICommand ShowEmailAddress
{
    get
    {
        return new Command(() => true, () => DialogService.Show(this.EmailAddress));
    }
}


Command is not available on base class library of .NET, we have to implement ICommand ourselves.

Found a sample implementation of ICommand here: http://www.markwithall.com/programming/2013/03/01/worlds-simplest-csharp-wpf-mvvm-example.html


Modified according to the need of code above:
public class Command : ICommand
{
    readonly Action _action;

    readonly Func<bool> _canExecute;

    
    public Command(Func<bool> canExecute, Action action)
    {
        _canExecute = canExecute;
        _action = action;
    }

    void ICommand.Execute(object parameter)
    {
        _action();
    }

    bool ICommand.CanExecute(object parameter)
    {
        // return true; // It's advisable to make this always true: http://www.markwithall.com/programming/2013/03/01/worlds-simplest-csharp-wpf-mvvm-example.html

        return _canExecute();
    }

#pragma warning disable 67
    public event EventHandler CanExecuteChanged;
#pragma warning restore 67
}


Happy Coding!

No comments:

Post a Comment