= Using ICommands in MVVM =

I've created my own generic type !DelegateCommand to illustrate my implementation. You will notice that my actions and predicates take an object. This allows me to pass an object in as a !CommandParameter. I'll show a XAML fragment first and then the !DelegateCommand.

{{{#!highlight html
...
<Button Content="Label" Command="{Binding DelegateCommand}" CommandParameter="String I want to pass in" />
...
}}}

{{{#!highlight csharp
using System;
using System.Windows.Input; //for ICommand

namespace GeneralEducationImporter.Model
{
    public class DelegateCommand<T> : ICommand
    {
        private readonly Predicate<T> _canExecute;
        private readonly Action<T> _execute;

        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }

}
}}}