C #: WinForm Command,
This article describes how to use commands as elegantly as wpf in the WinForm project to implement business operations. You may be exhausted by double-clicking the control to generate an event processing method to implement business operations, such as multiple controls (buttons, menus, toolbar, Status Bar, and other command controls) to do the same action, you also need to control their Enabled status to make the code structure lengthy and less readable. The following describes and implements the application of Command in WinForm.
Finally, the implementation of the delegate command (DegelateCommand) is attached.
1 /// <summary> 2 /// indicates a command that can be executed to delegate methods. 3 /// </summary> 4 public sealed class DelegateCommand: Command 5 {6 private Action <object> execute; 7 private Func <object, bool> canExecute; 8 /// <summary> 9 /// initialize the <see cref = "DelegateCommand"/> new instance. 10 /// </summary> 11 /// <param name = "execute"> specifies the method when the command is called. </Param> 12 // <param name = "canExecute"> method of execution when the command is determined to be executable. </Param> 13 public DelegateCommand (Action <object> execute, Func <object, bool> canExecute = null) 14 {15 this.exe cute = execute; 16 this. canExecute = canExecute; 17} 18 /// <summary> 19 // defines the method used to determine whether the command can be executed in its current state. 20 /// </summary> 21 /// <param name = "parameter"> data used by this command. If this command does not need to pass data, the object can be set to null. </Param> 22 // <returns> if you can run this command, the value is true; otherwise, the value is false. </Returns> 23 public override bool CanExecute (object parameter) 24 {25 if (canExecute = null) 26 {27 return true; 28} 29 return canExecute (parameter ); 30} 31 32 // <summary> 33 // defines the method called when this command is called. 34 /// </summary> 35 /// <param name = "parameter"> data used by this command. If this command does not need to pass data, the object can be set to null. </Param> 36 public override void Execute (object parameter) 37 {38 if (CanExecute (parameter) 39 {40 execute (parameter); 41} 42} 43}DelegateCommand code
Supplement: Sorry, I forgot to attach the Demo. I want to add it now. Please download it from Baidu online storage.
If you have missed this article, you are welcome to criticize and correct it!