How can I use the RelayCommand in wpf?

Sauron picture Sauron · May 14, 2009 · Viewed 63.2k times · Source

How can I use the RelayCommand in wpf?

Answer

Martin Harris picture Martin Harris · May 14, 2009

Relay command doesn't exist in WPF, it is just a external class that raised to prominence after it was defined in this MSDN article. You need to write it yourself if you want to use it.

Otherwise you can you the Delegate command from the WPF toolkit here which has a little bit of extra functionality over the RelayCommand code.


Ah, the question changed while I was typing this answer. Assuming that you are using the RelayCommand as defined above you need to supply it with one or two delegates, one that returns a bool which determines whether the command is in a valid state to be run, and a second which returns nothing and actually runs the command. If you don't supply a "CanRun" delegate then the command will consider that it is always in a valid state. The code used in the article:

RelayCommand _saveCommand;
public ICommand SaveCommand
{
    get
    {
        if (_saveCommand == null)
        {
            _saveCommand = new RelayCommand(param => this.Save(),
                param => this.CanSave );
        }
        return _saveCommand;
    }
}

Declares a RelayCommand that will call the Save() method when triggered and return the CanSave property as a test for validity. When this command is bound to a button in WPF the IsEnabled property of the Button will match the CanSave property of the ViewModel and when the button is clicked (assuming it is enabled) the Save() method will be called on the ViewModel.