问题描述
当我实现ICommand
接口时,将创建以下方法
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
有趣的部分是
public void Execute(object parameter)
{
}
仅因为它指示期望1个参数.如果我不需要传递参数怎么办?在我的ViewModel中,我有以下代码
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;
}
}
OpenDialog
方法不需要该参数,但看起来好像我必须这样做,这样我才能满足Interface.
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?
推荐答案
是的,ICommand
总是需要一个对象,而RelayCommand
也总是需要一个对象.如果不需要它,则传递null,并且不要在您的方法中使用它,这很丑陋.
Yes, ICommand
always needs an object and RelayCommand
too. If you don't need it, you pass null and don't use it in your method, which is ugly.
我会改用Prism的DelegateCommand
.它存在于非通用版本中,该版本不使用参数:
I would use Prism's DelegateCommand
instead. This exists in a non-generic version, which doesn't take parameters:
Command = new DelegateCommand(DoSomething);
CommandWithParameter = new DelegateCommand<int>(DoSOmethingWithInt);
它在PRISM程序集中,您必须下载并参考.
Its in the PRISM assembly, which you have to download and reference.
using Microsoft.Practices.Prism;
或者,使用MVVMLight工具箱,该工具箱提供了一个命令类,其功能基本相同.无论如何,在没有MVVM框架的情况下使用MVVM是没有意义的.我可以推荐PRISM,因为它是DelegateCommand
或EventAggregator
的基本内容.
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 the EventAggregator
.
这篇关于ICommand是否总是需要对象作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!