Ich las eine MVVM tutorial und ich verlor im Commands Teil.MVVM ICommand und Delegate
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();
}
}
}
}
verstehe ich nicht den Zweck der RaiseCanExecuteChanged
Methode und die Linie EventHandler CanExecuteChanged = delegate { };
. Ich habe gelesen, dass EventHandler ein Delegat ist, aber welche Art von Delegat ist das? Was gibt die delegate { };
Anweisung zurück?
Zweck: http://stackoverflow.com/questions/6425923/canexecutechanged-event-of-icommand – Fruchtzwerg
Normalerweise Ihre 'UI' Elemente wie' Button's mit definierten 'Command's nennen' canExecute' Methode. Dies wird sie davon abhalten, 'NullReferenceException' zu werfen. Aus diesem Grund ist der canExecuteChanged als leerer Delegat definiert. Probieren Sie es selbst aus und sehen Sie, ob Sie eine Ausnahme mit einem einfachen 'Button' sehen können. – XAMlMAX