将视图模型中的抽象命令作为XAML / MVVM项目的一个有价值的实践.我明白了.而且,我在WinRT中看到ICommand;但是,我们如何实现呢?我没有找到一个实际工作的样本.有人知道吗
我所有的时间最喜欢的都是由PnP团队提供的DelegateCommand.它允许您创建一个键入的命令:
原文链接:https://www.f2er.com/windows/371552.htmlMyCommand = 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 }