【问题标题】:Capture command Parameter value in mvvm在 mvvm 中捕获命令参数值
【发布时间】:2014-08-24 11:13:43
【问题描述】:

我有两个单选按钮。我只想在 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()
            {

            }

【问题讨论】:

    标签: wpf


    【解决方案1】:

    使用 lambda 捕获参数(假设您使用的 RelayCommand 具有重载的构造函数,它将以 Action&lt;object&gt; 作为参数)

    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
    }
    

    【讨论】:

    • 嗨,我尝试使用stackoverflow.com/questions/5298910/… 解决方案。但我得到“非泛型类型不能与 RelayCommand 一起使用不能与类型化参数一起使用”错误。关于错误的任何想法。
    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2012-04-29
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    相关资源
    最近更新 更多