Search code examples
c#wpfmvvmdelegatecommand

Passing object type of parameter in a function called from Deleagte Command in WPF MVVM


Why does the following function take object type of parameters in WPF MVVM?

 public ViewModel()
 {
 SaveCommand2 = new DelegateCommand(SaveCommand_Execute);
 }

 bool SaveCommand_CanExecute(object arg)
 {
        return Model.Name != string.Empty;
 }

by default we are not passing anything as parameter in function, as such NULL is passed into it.

If we don't want to pass anything, better remove parameter from function. But it is not allowing. Why?


Solution

  • The DelegateCommand is a 'generic' implementation for creating commands. The WPF commands have an optional CommandParameter which is used to supply data to the command on execution. This is why the DelegateCommand has an argument of type object, if a command parameter binding is used, the parameter is passed via this argument.