使用MVVM将CommandParameter传递给Silverlight中的Command

时间:2010-12-19 13:15:00

标签: mvvm silverlight-4.0 command relaycommand commandparameter

我正在学习Silverlight并关注MVVM和命令。

好的,所以我看到了基本的RelayCommand实现:

public class RelayCommand : ICommand
{
    private readonly Action _handler;
    private bool _isEnabled;

    public RelayCommand(Action handler)
    {
        _handler = handler;
    }

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
    }

    public bool CanExecute(object parameter)
    {
        return IsEnabled;
    }

    public event EventHandler CanExecuteChanged;

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

如何使用此命令向下传递参数?

我已经看到你可以传递这样的CommandParameter

<Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... />

在我的ViewModel中,我需要创建命令,但RelayCommand期待Action代理。我可以使用RelayCommand<T>实施Action<T> - 如果是,我该怎么做以及如何使用它?

任何人都可以给我任何关于MVVM的CommandParameters的实际例子,它们不涉及使用第三方库(例如MVVM Light),因为我想在使用现有库之前完全理解它。

感谢。

2 个答案:

答案 0 :(得分:4)

public class Command : ICommand
{
    public event EventHandler CanExecuteChanged;

    Predicate<Object> _canExecute = null;
    Action<Object> _executeAction = null;

    public Command(Predicate<Object> canExecute, Action<object> executeAction)
    {
        _canExecute = canExecute;
        _executeAction = executeAction;
    }
    public bool CanExecute(object parameter)
    {
        if (_canExecute != null)
            return _canExecute(parameter);
        return true;
    }

    public void UpdateCanExecuteState()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, new EventArgs());
    }

    public void Execute(object parameter)
    {
        if (_executeAction != null)
            _executeAction(parameter);
        UpdateCanExecuteState();
    }
}

是命令的基类

这是ViewModel中的命令属性:

 private ICommand yourCommand; ....

 public ICommand YourCommand
    {
        get
        {
            if (yourCommand == null)
            {
                yourCommand = new Command(  //class above
                    p => true,    // predicate to check "CanExecute" e.g. my_var != null
                    p => yourCommandFunction(param1, param2));
            }
            return yourCommand;
        }
    }

在XAML中设置Binding to Command Property,如:

 <Button Command="{Binding Path=YourCommand}" .../>

答案 1 :(得分:1)

也许这篇文章解释了你在寻找什么。几分钟前我也遇到了同样的问题。

http://www.eggheadcafe.com/sample-code/SilverlightWPFandXAML/76e6b583-edb1-4e23-95f6-7ad8510c0f88/pass-command-parameter-to-relaycommand.aspx