Question

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?

Was it helpful?

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.

OTHER TIPS

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.

Try this,

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top