簡體   English   中英

MVVM ICommand和委托

[英]MVVM ICommand and delegate

我閱讀了一個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(); 
         } 
      } 
   } 
}

我不了解RaiseCanExecuteChanged方法和EventHandler CanExecuteChanged = delegate { };行的目的EventHandler CanExecuteChanged = delegate { }; 我讀到EventHandler是一個委托,但它是什么樣的委托? delegate { };是什么delegate { }; 聲明回歸?

回答你的第二個問題,是的, EventHandlervoid EventHandler(object sender, EventArgs args)類型的委托void EventHandler(object sender, EventArgs args) 以下行是分配給EventHandler的默認(空)匿名委托。 可能是為了防止NullReferenceException 下面的行也可以寫成:

EventHandler canExecute = delegate { };

要了解RaiseCanExecuteChanged的用法,請在此處閱讀此答案: httpsRaiseCanExecuteChanged

更新 - (@Will)

當執行命令的能力發生變化時,可以通過視圖模型中的代碼調用RaiseCanExecuteChanged。 例如,當UserName和Password為空時,保存按鈕返回false,但是當它們被填滿時,VM調用RaiseCanExecuteChanged,當按鈕詢問命令是否可以觸發時,它現在響應為正。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM