对于XAML / MVVM项目,将命令抽象到视图模型中是一种有价值的实践。我明白了。而且,我在WinRT中看到了ICommand;但是,我们如何实施呢?我还没有找到实际可行的示例。有人知道吗

最佳答案

我一直以来最喜欢的是Microsoft模式和实践团队提供的DelegateCommand。它允许您创建键入的命令:



MyCommand = new DelegateCommand<MyEntity>(OnExecute);
...
private void OnExecute(MyEntity entity)
{...}


它还提供了引发CanExecuteChanged事件的方法(以禁用/启用命令)

MyCommand.RaiseCanExecuteChanged();


这是代码:

public class DelegateCommand<T> : ICommand
{
    private readonly Func<T, bool> _canExecuteMethod;
    private readonly Action<T> _executeMethod;

    #region Constructors

    public DelegateCommand(Action<T> executeMethod)
        : this(executeMethod, null)
    {
    }

    public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
    {
        _executeMethod = executeMethod;
        _canExecuteMethod = canExecuteMethod;
    }

    #endregion Constructors

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    bool ICommand.CanExecute(object parameter)
    {
        try
        {
            return CanExecute((T)parameter);
        }
        catch { return false; }
    }

    void ICommand.Execute(object parameter)
    {
        Execute((T)parameter);
    }

    #endregion ICommand Members

    #region Public Methods

    public bool CanExecute(T parameter)
    {
        return ((_canExecuteMethod == null) || _canExecuteMethod(parameter));
    }

    public void Execute(T parameter)
    {
        if (_executeMethod != null)
        {
            _executeMethod(parameter);
        }
    }

    public void RaiseCanExecuteChanged()
    {
        OnCanExecuteChanged(EventArgs.Empty);
    }

    #endregion Public Methods

    #region Protected Methods

    protected virtual void OnCanExecuteChanged(EventArgs e)
    {
        var handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    #endregion Protected Methods
}

关于windows-8 - 是否有任何WinRT iCommand/CommandBinding实现示例?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11960488/

10-12 23:31