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?
UIelements likeButtons with definedCommands will callcanExecutemethod. This will stop them from throwingNullReferenceException. That's why the canExecuteChanged is defined as an empty delegate. try it yourself and see if you can see any exception with a simpleButton.