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

2.4k Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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.

0
On

If you implement your own DelegateCommand, you can have constructors that receive parameterless actions, as shown in the following code:

public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
{
  if (execute == null)
    throw new ArgumentNullException("execute", "execute cannot be null");
  if (canExecute == null)
    throw new ArgumentNullException("canExecute", "canExecute cannot be null");

  _execute = execute;
  _canExecute = canExecute;
}

public DelegateCommand(Action<object> execute)
  : this(execute, (o) => true)
{

}

public DelegateCommand(Action execute)
  : this((o) => execute())
{

}

With that last constructor overload you could do

var someCommand = new DelegateCommand(SomeMethod);

where Method is parameterless

0
On

I think you can create custom implemenation of delegate command to overcome this issue. You can have a look at Simplify DelegateCommand for the most common scenario to get more information.

0
On

Try this,

 public ViewModel()
 {
 SaveCommand2 = new DelegateCommand(new Action(() =>
                {
                  //Your action stuff.
                }), SaveCommand_CanExecute);
 }

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