在MVVM中接收CommandParameter值

时间:2009-10-14 08:51:49

标签: wpf mvvm parameters commandbinding

我正在绑定我的命令,如:

<Button Command="{Binding NextCommand}" 
    CommandParameter="Hello" 
    Content="Next" /> 

在这里,我还绑定了它的CommandParameter属性,现在如何从NextCommand获取它的值。

public ICommand NextCommand
    {
        get
        {
            if (_nextCommand == null)
            {
                _nextCommand = new RelayCommand(
                    param => this.DisplayNextPageRecords()
                    //param => true
                    );
            }
            return _nextCommand;
        }
    }

其功能定义:

public ObservableCollection<PhonesViewModel> DisplayNextPageRecords()
    {

            //How to fetch CommandParameter value which is set by 
            //value "Hello" at xaml. I want here "Hello"
            PageNumber++;
            CreatePhones();
            return this.AllPhones;

    }

如何获取CommandParameter值?

提前致谢。

1 个答案:

答案 0 :(得分:33)

更改方法定义:

public ObservableCollection<PhonesViewModel> DisplayNextPageRecords(object o)
{
    // the method's parameter "o" now contains "Hello"
    PageNumber++;
    CreatePhones();
    return this.AllPhones;
}

看看在创建RelayCommand时,它的“Execute”lambda如何获取参数?将其传递给您的方法:

_nextCommand = new RelayCommand(param => this.DisplayNextPageRecords(param));