2

我知道我已经对此提出了问题,但有些事情只是令人困惑。我正在做一个关于 WPF MVVM 模式的教程,但似乎我做错了,因为在教程中,它没有详细介绍如何实现 ICommand 接口。(不确定它到底有多正确?!!)

我有以下 ICommand 实现:

class ViewCommand : ICommand
    {
        #region ICommand Members

        private Predicate<object> _canExecute;
        private Predicate<bool> _execute(object param);

        public ViewCommand(Action<object> action)
        {

        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public event EventHandler CanExecuteChanged 
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        #endregion
    }

现在这个用途:

class StartViewModel : ViewModel
    {
        public ViewCommand startViewCommand;

        public ViewCommand StartCommand
        {
            get
            {
                if (startViewCommand == null)
                    startViewCommand = new ViewCommand(
                        param => this.StartApplication()); // StartApplication returns void
                return startViewCommand;
            }
        }

我无法弄清楚我的ViewCommand类的构造函数应该做什么?在 StartViewModel类中,它在构造函数中使用 lambda 表达式,因此需要一些委托,但我不确定它是什么以及如何与 Execute 和 CanExecute 一起工作。我放了一个Action<object>,但它可能是错误的......

最后,有人可以向我指出一个关于如何实现 ICommand 的教程来解释它吗?

谢谢!

4

2 回答 2

3

看看 Josh Smith 的教程,注意他实现它的中继命令。

于 2010-02-07T23:26:51.880 回答
0

你的_execute代表不应该是 a Predicate<bool>,它应该是 a Action<object>。无论如何,您为什么不使用现有的类RelayCommand,如 Josh Smith 或 MVVM 工具包DelegateCommand

于 2010-02-07T23:46:24.830 回答