【发布时间】:2016-12-12 21:30:58
【问题描述】:
我读了MVVM tutorial,但我迷失在命令部分。
using System;
using System.Windows.Input;
namespace MVVMDemo {
public class MyICommand : ICommand {
Action _TargetExecuteMethod;
Func<bool> _TargetCanExecuteMethod;
public MyICommand(Action executeMethod) {
_TargetExecuteMethod = executeMethod;
}
public MyICommand(Action executeMethod, Func<bool> canExecuteMethod){
_TargetExecuteMethod = executeMethod;
_TargetCanExecuteMethod = canExecuteMethod;
}
public void RaiseCanExecuteChanged() {
CanExecuteChanged(this, EventArgs.Empty);
}
bool ICommand.CanExecute(object parameter) {
if (_TargetCanExecuteMethod != null) {
return _TargetCanExecuteMethod();
}
if (_TargetExecuteMethod != null) {
return true;
}
return false;
}
// Beware - should use weak references if command instance lifetime
is longer than lifetime of UI objects that get hooked up to command
// Prism commands solve this in their implementation public event
EventHandler CanExecuteChanged = delegate { };
void ICommand.Execute(object parameter) {
if (_TargetExecuteMethod != null) {
_TargetExecuteMethod();
}
}
}
}
我不明白RaiseCanExecuteChanged 方法和EventHandler CanExecuteChanged = delegate { }; 行的用途。
我读到 EventHandler 是一个委托,但它是什么样的委托?
delegate { }; 语句返回什么?
【问题讨论】:
-
通常你的
UI元素,如Buttons 定义的Commands 将调用canExecute方法。这将阻止他们抛出NullReferenceException。这就是为什么 canExecuteChanged 被定义为空委托的原因。自己尝试一下,看看您是否可以通过简单的Button看到任何异常。