How can I use the RelayCommand
in wpf?
2 Answers
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.

- 28,277
- 7
- 90
- 101
-
1I had an advantage because I looked it up yesterday for this answer: http://stackoverflow.com/questions/858268/in-mvvm-what-is-the-best-way-for-the-viewmodel-to-respond-to-user-actions-in-the/858303#858303 – Martin Harris May 14 '09 at 10:27
-
3I wish MSDN's articles code samples weren't all jumbled together, been like that for months now, anyone know a mirror or something that shows them normal? – Kyle Gobel Aug 31 '13 at 21:53
-
Incorrect/out of date Relay command does exist, but its a part of the https://mvvmlight.codeplex.com/ toolkit – MikeT Nov 04 '16 at 10:18
As an alternative to creating RelayCommand
wrappers for all your methods can I suggest a free library and source that will allow you to use the binding {BindTo Save()}
. I created it to simplify my bindings. It also makes relative binding much easier. You can find it here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html

- 27,650
- 10
- 79
- 80
-
2Looks very nice, though didn't test it. But I suggest you to improve the blog post and explain the implementation details. Although posting the code to Github would be very nice. And also consider putting more (some!) code on this answer on StackOverflow. – Mohammad Dehghan Oct 02 '13 at 05:06
-
+1 for @MD.Unicorn's suggestion to post the code on GitHub (or similar). It might also be nice if the library was available as a NuGet package. – Richard J Foster Sep 04 '14 at 14:52
-
1