我正在应用MVVM模式的乔希史密斯和有困难。我在这里一直在研究这个问题,似乎不能很好地理解语法。
在我看来,下面的代码遵循了所需的语法,但是Visual报告了错误--“委托'System.Action‘不接受'2’参数‘”。
有人能看到我在哪里犯错误吗?谢谢!
+汤姆
RelayCommand _relayCommand_MoveUp;
public ICommand RelayCommand_MoveUp
{
get
{
if (_relayCommand_MoveUp == null)
{
_relayCommand_MoveUp = new RelayCommand(
(sender, e) => this.Execute_MoveUp(sender, e), **ERROR REPORTED HERE**
(sender, e) => this.CanExecute_MoveUp(sender, e));
return _relayCommand_MoveUp;
}
}
}
private void Execute_MoveUp(object sender, ExecutedRoutedEventArgs e)
{
if (_selectedFolder != null)
{
_selectedFolder.SelectParent();
}
}
private void CanExecute_MoveUp(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (_selectedFolder != null) && (_selectedFolder.Parent != null);
}
//And from Josh Smith:
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute);
public RelayCommand(Action<object> execute, Predicate<object> canExecute);
public event EventHandler CanExecuteChanged;
[DebuggerStepThrough]
public bool CanExecute(object parameter);
public void Execute(object parameter);
}发布于 2009-05-22 23:58:59
RelayCommand不是一个RoutedCommand,我认为这就是你最终感到困惑的地方。
中继命令的构造函数采用行动代表和可选的谓词委托。这些委托不接受EventArgs,而只接受单个对象参数,这就是您遇到错误的原因。谓词还需要返回类型bool,这是您将得到的下一个错误。在CanExecute谓词中,您只需返回true/false,而不是像对RoutedCommand那样设置e.CanExecute。
它应该是这样的:
public ICommand RelayCommand_MoveUp
{
get
{
if (_relayCommand_MoveUp == null)
{
_relayCommand_MoveUp = new RelayCommand(Execute_MoveUp, CanExecute_MoveUp);
}
return _relayCommand_MoveUp;
}
}
private void Execute_MoveUp(object sender)
{
if (_selectedFolder != null)
{
_selectedFolder.SelectParent();
}
}
private void CanExecute_MoveUp(object sender)
{
return (_selectedFolder != null) && (_selectedFolder.Parent != null);
}编辑(从注释中的讨论中添加):
如果您想使用更像RoutedCommands的东西,这将使ViewModels更依赖于WPF特定的视图,那么有一些很好的选项可用。
这个讨论实现了将RoutedCommands与MVVM结合使用的整个想法。
下面是是对乔希·史密斯和比尔·肯普夫提出的问题的一个非常可靠的解决方案。
发布于 2009-08-25 04:35:39
这个周末(8月22日),乔希·史密斯( Josh Smith )为他的MvvmFoundation项目签入了对codeplex的新更改,该项目通过参数改变了RelayCommand对委托的工作方式。当心!
要将一个参数传递给委托,您需要使用他的新RelayCommand构造函数:
public ICommand GotoRegionCommand
{
get
{
if (_gotoRegionCommand == null)
_gotoRegionCommand = new RelayCommand<String>(GotoRegionCommandWithParameter);
return _gotoRegionCommand;
}
}
private void GotoRegionCommandWithParameter(object param)
{
var str = param as string;
}https://stackoverflow.com/questions/900437
复制相似问题