4

我只是在学习 Silverlight 并查看 MVVM 和 Commanding。

好的,所以我已经看到了基本的 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>using Action<T>- 如果可以,我该怎么做以及如何使用它?

谁能给我任何关于使用 MVVM 的 CommandParameters 的实际示例,这些示例不涉及使用 3rd-party 库(例如 MVVM Light),因为我想在使用现有库之前完全理解它。

谢谢。

4

2 回答 2

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 中设置绑定到命令属性,如:

 <Button Command="{Binding Path=YourCommand}" .../>
于 2010-12-20T14:43:49.287 回答
1

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

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

于 2010-12-19T15:37:05.343 回答