【问题标题】:MVVM ICommand and delegateMVVM ICommand 和委托
【发布时间】: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 看到任何异常。

标签: c# wpf mvvm


【解决方案1】:

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

EventHandler canExecute = delegate { };

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

更新 -(@Will)

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

【讨论】:

  • Psst,当要执行的命令的能力发生变化时,视图模型中的代码可以调用RaiseCanExecuteChanged。例如,当 UserName 和 Password 为空时,保存按钮返回 false,但当它们被填充时,VM 会调用 RaiseCanExecuteChanged,当按钮询问命令是否可以触发时,它现在会做出肯定的响应。
  • 解释得很好。 +1。
  • (psst,您可以将其添加到您的答案中以使其完整:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2016-04-23
相关资源
最近更新 更多