简体   繁体   English

MVVM Light RelayCommand参数

[英]MVVM Light RelayCommand Parameters

I'm having an issue with passing a parameter to a relaycommand using the GalaSoft MVVM Light framework. 我在使用GalaSoft MVVM Light框架将参数传递给relaycommand时遇到问题。 I know that mvvm light's implementation of relaycommand doesn't use lambda parameters, so I did some research and found a way that people worked around it by doing something like this: 我知道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;
}

However, I keep getting an error on the line _projmenuItem_Edit = new RelayCommand(ProjEditNode); 但是,我继续在行_projmenuItem_Edit = new RelayCommand(ProjEditNode);上收到错误_projmenuItem_Edit = new RelayCommand(ProjEditNode); that says Argument 1: cannot convert from 'method group' to 'System.Action' Argument 1: cannot convert from 'method group' to 'System.Action'

What am I missing? 我错过了什么?

I believe this will work: 我相信这会奏效:

_projmenuItem_Edit = new RelayCommand<object>((txt)=>ProjEditNode(txt));

-- EDIT -- - 编辑 -

You'll need to define your RelayCommand with the type as well: 您还需要使用类型定义RelayCommand:

eg 例如

public RelayCommand<string> myCommand { get; private set; }
myCommand = new RelayCommand<string>((s) => Test(s));

private void Test(string s)
{
    throw new NotImplementedException();
}

I don't think that RelayCommand() has a constructor that is not empty. 我不认为RelayCommand()有一个非空的构造函数。 you're trying to pass the wrong kind of method to it. 你试图将错误的方法传递给它。

If you want the RelayCommand to support Command Parameters, you should use RelayCommand<T> where T can be any type of parameter. 如果希望RelayCommand支持命令参数,则应使用RelayCommand<T> ,其中T可以是任何类型的参数。 In your situation it would be RelayCommand<String> which would accept a method with void(string) signature. 在你的情况下,它将是RelayCommand<String> ,它接受一个带有void(string)签名的方法。 (and therefor would also be strongly typed and won't use the ugly object) (因此也将强类型,不会使用丑陋的对象)

Another way to declare relay commands, will help to reduce your code 声明中继命令的另一种方法是帮助减少代码

public RelayCommand ChartCommand
{
    set
    {
        RelayCommand<string> chartCommand = 
            new RelayCommand<string>(e => ExecuteChartCommand(e));               
    }
}

public void ExecuteChartCommand(string vendor)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM