微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

windows-8 – 任何WinRT iCommand / CommandBinding实现示例?

将视图模型中的抽象命令作为XAML / MVVM项目的一个有价值的实践.我明白了.而且,我在WinRT中看到ICommand;但是,我们如何实现呢?我没有找到一个实际工作的样本.有人知道吗
我所有的时间最喜欢的都是由PnP团队提供的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
}

原文地址:https://www.jb51.cc/windows/371552.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐