MVVM Light RelayCommand Parameters

爷,独闯天下 提交于 2019-12-27 23:35:34

问题


I'm having an issue with passing a parameter to a relaycommand using the GalaSoft MVVM Light framework. 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:

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); that says Argument 1: cannot convert from 'method group' to 'System.Action'

What am I missing?


回答1:


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:

e.g.

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

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



回答2:


I don't think that RelayCommand() has a constructor that is not empty. 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. In your situation it would be RelayCommand<String> which would accept a method with void(string) signature. (and therefor would also be strongly typed and won't use the ugly object)




回答3:


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)
{

}


来源:https://stackoverflow.com/questions/5298910/mvvm-light-relaycommand-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!