加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-13 20:24:19 所属栏目:Windows 来源:网络整理
导读:将视图模型中的抽象命令作为XAML / MVVM项目的一个有价值的实践.我明白了.而且,我在WinRT中看到ICommand;但是,我们如何实现呢?我没有找到一个实际工作的样本.有人知道吗 我所有的时间最喜欢的都是由PnP团队提供的DelegateCommand.它允许您创建一个键入的命
将视图模型中的抽象命令作为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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读