When I implement the ICommand
interface, the following methods are created
#region ICommand Members
public bool CanExecute(object parameter)
{
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
}
#endregion
The interesting part is
public void Execute(object parameter)
{
}
Simply because it indicates that it expects 1 parameter. What if I don't need to pass a parameter? In my ViewModel I have the following code
public class DownloadViewModel : BaseViewModel
{
public ICommand BrowseForFile { get; set; }
public string File { get; set; }
public DownloadViewModel()
{
BrowseForFile = new RelayCommand(new Action<object>(OpenDialog));
}
private void OpenDialog(object o)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
File = dialog.SelectedPath;
}
}
The OpenDialog
method does not require the parameter but it appears as if I have to just so I can satisfy the Interface.
Am I doing this right or have I missed the point?
Yes,
ICommand
always needs an object andRelayCommand
too. If you don't need it, you pass null and don't use it in your method, which is ugly.I would use Prism's
DelegateCommand
instead. This exists in a non-generic version, which doesn't take parameters:Its in the PRISM assembly, which you have to download and reference.
PRISM
Alternatively, use the MVVMLight toolkit, which provides a command class which does basically the same thing. There is no point in using MVVM without a MVVM framework anyway. I can recommend PRISM, also for it's basic stuff like the
DelegateCommand
or theEventAggregator
.The fact that
Execute
takes a parameter is irrelevant to the method from yourViewModel
. The only thing that affects what parametersOpenDialog
needs is your implementation ofICommand
.If your implementation is, for example:
Then no parameters will be required for your
OpenDialog
method, as you can create a command as follows:You can, however, require any signature you like for the method you are passing to your command.
The most common, off-the-shelf implementations of
RelayCommand
can take methods with either 0 or 1 parameter and will be called fromExecute
appropriately.