How can I use the RelayCommand in wpf?
Asked Answered
S

2

41

How can I use the RelayCommand in wpf?

Scouring answered 14/5, 2009 at 10:16 Comment(0)
B
53

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.

Birkner answered 14/5, 2009 at 10:20 Comment(3)
I had an advantage because I looked it up yesterday for this answer: #858768Birkner
I 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?Cohl
Incorrect/out of date Relay command does exist, but its a part of the mvvmlight.codeplex.com toolkitDolley
G
6

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

Grannias answered 6/8, 2012 at 18:0 Comment(3)
Looks 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.Loidaloin
+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.Fanaticize
The link broke, I thinkKidskin

© 2022 - 2024 — McMap. All rights reserved.