gpt4 book ai didi

c# - MVVM ICommand 和委托(delegate)

转载 作者:太空宇宙 更新时间:2023-11-03 23:06:05 26 4
gpt4 key购买 nike

我读了一个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),但它是什么样的委托(delegate)呢?delegate { }; 语句返回什么?

最佳答案

回答你的第二个问题,是的 EventHandlervoid EventHandler(object sender, EventArgs args) 类型的委托(delegate)。以下行是分配给 EventHandler 的默认(空)匿名委托(delegate)。可能是为了防止 NullReferenceException。下面一行也可以写成:

EventHandler canExecute = delegate { };

要了解 RaiseCanExecuteChanged 的用法,请阅读此处的答案:https://stackoverflow.com/a/4531378/881798

更新 -(@Will)

当要执行的命令的能力发生变化时, View 模型中的代码可以调用 RaiseCanExecuteChanged。例如,保存按钮在 UserName 和 Password 为空时返回 false,但当它们被填充时,VM 调用 RaiseCanExecuteChanged,当按钮询问命令是否可以触发时,它现在以肯定的方式响应。

关于c# - MVVM ICommand 和委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com