Why use RelayCommand or DelegateCommand instead of just executing ICommand?

I just found out about MVVM in WPF, I am completely new to both WPF and MVVM (I understand how it works, but never used it ...)

Every single tutorial / article that I find on the Internet uses either RelayCommand or DelegateCommand.

In my case, these patterns oblige the virtual machine to violate the SRP principle, since it will contain the logic of commands inside itself.

Why not just use the custom implementation of the ICommand interface? Similar:

Imagine that you show a person and save him in the database:

My haml will be as follows:

<StackPanel> <TextBlock Width="248" Height="24" Text="The name is:: " /> <TextBlock Width="248" Height="24" Text="{Binding Name}"> </TextBlock> <TextBox HorizontalAlignment="Left" Name="textBox1" Width="120" Height="23" VerticalAlignment="Top" Text="{Binding Name}" /> <Button Name="Salvar" VerticalAlignment="Bottom" Command="{Binding SavePerson}" CommandParameter="{Binding}">Save</Button> </StackPanel> 

And this is my virtual machine:

 public class PersonVM: INotifyPropertyChanged { private string nameValue; public string Name { get{ return nameValue; } set { if (value != this.nameValue) { this.nameValue= value; NotifyPropertyChanged("Name"); } } } public ICommand SavePerson{ get { return new SavePersonCommand(); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } #endregion } 

And this is my command:

 public class SavePersonCommand: ICommand { #region ICommand Members public bool CanExecute(object parameter) { return (parameter as PersonVM) != null; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { PersonVM person = parameter as PersonVM; if(person != null) //Actually Save the person... } #endregion } 

What is the problem with my approach?

+8
source share
2 answers

If you do not use any basic command (framework or your own command), you will write the same code again and again. For example: you do not raise the CanExecuteChanged event in your own command. The same goes for the implementation of INotifyPropertyChanged . That's why everyone uses one or another MVVM structure.

+1
source

Nothing ... but DelegateCommand is useful if you have a really specific command just for your ViewModel, and you don't want to show it to others because it is really simple for your ViewModel. I also like DelegateCommands because they don’t need another class that you just pass to the ViewModel, it's less code to write. Your approach is useful if the supplied ViewModel is a base ViewModel that is shared, which also allows you to share your Team.

+3
source

All Articles