捕获命令mvvm中的参数值

时间:2014-08-24 11:13:43

标签: wpf

我有两个单选按钮。我只想捕获viewmodel中选定的单选按钮值。我已经定义了一个方法GetLOB(),我想在其中捕获commandParameter值。

这是我的代码

<RadioButton GroupName="Os" Content="Payroll" IsChecked="{Binding ObjEntrySheetManagerViewModel.CheckedProperty}" Command="LobType" CommandParameter="Payroll" Grid.Row="4"  Grid.Column="0" Margin="25,15,0,0"/>
<RadioButton GroupName="Os" Content="Sales" Grid.Row="4"  Grid.Column="1" Command="LobType" CommandParameter="Payroll" Margin="5,15,0,0"/>


     private RelayCommand _LobType;
            public ICommand LobType
            {
                get
                {
                    if (_LobType == default(RelayCommand))
                    {
                        _LobType = new RelayCommand(GetLOB);
                    }
                    return _LobType;
                }
            }

            private void GetLOB()
            {

            }

1 个答案:

答案 0 :(得分:1)

使用lambda 捕获参数(假设您使用的RelayCommand重载构造函数,将Action<object>作为参数)

public ICommand LobType
{
    get
    {
       if (_LobType == default(RelayCommand))
       {
          _LobType = new RelayCommand(param => GetLOB(param));
       }
       return _LobType;
    }
}

private void GetLOB(object parameter)
{

}

来自MSDN的中继命令示例(如果您需要):

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute; 
    readonly Predicate<object> _canExecute;

    #endregion

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    { 
        if (execute == null) 
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameter) 
    { 
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged 
    { 
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion
}