我读了MVVM 教程,但在命令部分迷失了方向。
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白该RaiseCanExecuteChanged方法和该行的目的EventHandler CanExecuteChanged = delegate { };。我读到 EventHandler 是一个委托,但是它是什么样的委托呢?该语句返回什么delegate { };?
回答你的第二个问题,是的EventHandler,是类型的委托void EventHandler(object sender, EventArgs args)。以下行是分配给事件处理程序的默认(空)匿名委托。可能是为了预防NullReferenceException。下面这行也可以写成:
EventHandler canExecute = delegate { };
Run Code Online (Sandbox Code Playgroud)
要了解用法,RaiseCanExecuteChanged请阅读此答案:https ://stackoverflow.com/a/4531378/881798
更新-(@Will)
当要执行的命令的能力发生变化时,视图模型中的代码可以调用RaiseCanExecuteChanged。例如,当用户名和密码为空时,保存按钮返回 false,但当它们被填充时,VM 会调用 RaiseCanExecuteChanged,并且当按钮询问命令是否可以触发时,它现在会做出肯定响应。