I’m confused about command pattern. There are so many different explanations about the commands. I thought the code below was delegatecommand, but after reading about the relaycommand, I am in doubt.
What is the difference between relaycommand, delegatecommand and routedcommand. Is it possible to show in examples that have relevance to my posted code?
class FindProductCommand : ICommand
{
ProductViewModel _avm;
public FindProductCommand(ProductViewModel avm)
{
_avm = avm;
}
public bool CanExecute(object parameter)
{
return _avm.CanFindProduct();
}
public void Execute(object parameter)
{
_avm.FindProduct();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
Your
FindProductCommandclass implements theICommandinterface, which means it can be used as a WPF command. It is neither aDelegateCommandnor aRelayCommand, nor is it aRoutedCommand, which are other implementations of theICommandinterface.FindProductCommandvsDelegateCommand/RelayCommandGenerally, when an implementation of
ICommandis namedDelegateCommandorRelayCommand, the intention is that you don’t have to write a class that implements theICommandinterface; rather, you pass the necessary methods as parameters to theDelegateCommand/RelayCommandconstructor.For example, instead of your entire class, you could write:
(Another, perhaps greater benefit than the savings in boilerplate code — if you instantiate the
DelegateCommand/RelayCommandwithin your viewmodel, your command has access to the internal state of that viewmodel.)Some implementations of
DelegateCommand/RelayCommand:ICommandcalledDelegateCommandDelegateCommandRelayCommandby Josh SmithRelated:
FindProductCommandvsRoutedCommandYour
FindProductCommandwill executeFindProductwhen triggered.WPF’s built-in
RoutedCommanddoes something else: it raises a routed event which can be handled by other objects in the visual tree. This means you can attach a command binding to those other objects to executeFindProduct, while attaching theRoutedCommanditself specifically to one or more objects that trigger the command, e.g. a button, a menu item, or a context menu item.Some related SO answers: