简体   繁体   中英

MVVM ICommand and delegate

I read a MVVM tutorial and I got lost in the Commands part.

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(); 
         } 
      } 
   } 
}

I'm not understanding the purpose of the RaiseCanExecuteChanged method and the line EventHandler CanExecuteChanged = delegate { }; . I read that EventHandler is a delegate, but what kind of delegate is it? What does the delegate { }; statement return?

Answering your second question, yes EventHandler is delegate of type void EventHandler(object sender, EventArgs args) . The following line is an default(Empty) anonymous delegate assigned to the EventHandler. May be to prevent NullReferenceException . Below line can also be written as:

EventHandler canExecute = delegate { };

To get the understanding of the usage of RaiseCanExecuteChanged read this answer here: https://stackoverflow.com/a/4531378/881798

Update - (by @Will)

RaiseCanExecuteChanged can be called by the code in the view model when the ability of the command to be executed has changed. For example, the save button returns false when UserName and Password are empty, but when they are filled, the VM calls RaiseCanExecuteChanged, and when the button asks the command if it can fire, it now responds in the positive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM