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

好的,所以我已经看到了基本的继电器实现:

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的命令参数上给我任何实用示例,而这些示例不涉及使用第三方库(例如MVVM Light),因为我想在使用现有库之前完全理解它。

谢谢。

有帮助吗?

解决方案

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}" .../>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top