我在使用GalaSoft MVVM Light框架将参数传递给relaycommand时遇到问题.我知道mvvm light的relay命令的实现不使用lambda参数,所以我做了一些研究,并找到了一种方法,人们通过做这样的事情来解决它:
public RelayCommand ProjMenuItem_Edit
{
get
{
if (_projmenuItem_Edit == null)
{
//This should work....
_projmenuItem_Edit = new RelayCommand(ProjEditNode);
}
return _projmenuItem_Edit;
}
}
private void ProjEditNode(object newText)
{
var str = newText as string;
OrganLocationViewModel sel =
ProjectOrganLocationView.GetExtendedTreeView().GetTopNode();
//Console.WriteLine(sel.OrganDisplayName);
sel.OrganDisplayName = str;
}
Run Code Online (Sandbox Code Playgroud)
但是,我一直在_projmenuItem_Edit = new RelayCommand(ProjEditNode);
说错误Argument 1: cannot convert from 'method group' to 'System.Action'
我错过了什么?
我正在学习WPF和MVVM,我想我已经掌握了大部分内容以及它是如何工作的但是我遇到了一些关于使用我不理解的RelayCommand(或DelegateCommand)的事情.我认为这与代表的工作方式有关.
请注意,以下代码目前仅在测试解决方案中,因此没有实时代码.此外,我正在考虑这个不需要参数如close的命令,并了解它为什么工作.
因此,如果我采用Josh Smith创建的RelayCommand(http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030),我可以设置如下命令:
RelayCommand updateTextContentCommand;
public ICommand UpdateTextContentCommand
{
get
{
if (updateTextContentCommand == null)
{
updateTextContentCommand = new RelayCommand(
param => this.UpdateTextContentCommand_Execute());
}
return updateTextContentCommand;
}
}
Run Code Online (Sandbox Code Playgroud)
使用此execute方法:
public void UpdateTextContentCommand_Execute()
{
this.TextContent = DateTime.Now.ToString();
}
Run Code Online (Sandbox Code Playgroud)
我使用了一个简单的绑定到TextBlock来查看结果,命令绑定到一个按钮.这很好用.我没有得到的是使用lambda表达式来创建命令.该Action<object>
预期参数,不是吗?那么为什么这段代码有效呢?
如果我将上面的代码更改为
if (updateTextContentCommand == null)
{
updateTextContentCommand = new RelayCommand(
this.UpdateTextContentCommand_Execute());
}
Run Code Online (Sandbox Code Playgroud)
我收到这些错误:
*'MVVM.RelayCommandTesting.Framework.RelayCommand.RelayCommand(System.Action)'的最佳重载方法匹配有一些无效的参数
参数1:无法从'void'转换为'System.Action'*
并删除()
后Execute给出此错误:
参数1:无法从'方法组'转换为'System.Action'
但是,如果我改变这样的代码:
if (updateTextContentCommand == null)
{
updateTextContentCommand = new RelayCommand(
this.UpdateTextContentCommand_Execute);
}
public void UpdateTextContentCommand_Execute(object param)
{
this.TextContent …
Run Code Online (Sandbox Code Playgroud)