In this post, I am going to explain about commanding in WPF.
What are Commands?
Commands are very useful, Commands provides input handling at semantic level rather than device level. Lets look at what advantage we get if you use Commanding in WPF.
It separates the Logic and Control which invokes the Command.
Command’s logic can be invoked from multiple sources.
Allows Command logic to be customized based on Source (which invokes the command) and the Target (on which Command is invoked).
it can determine whether an Action is available (CanExecute property) ex: with copying anything Paste command is not enabled.
Main Concept of Commanding
Action: This is defined in Executed event.
Command Source: This is the source control which invokes the command. It could be any control. ex:
<MenuItem Command=”ApplicationCommands.Properties” />
Command Target: The control on which command is being executed.
Command Binding: This maps the command logic to command.
Command are implemented by implementing iCommand Interface. iCommand exposes below 2 methods
Execute: The command’s logic
CanExecute: Determines whether command can be executed on the target
and an Event
- CanExecuteChanged.Execute: When Command Manager detects a change in command source.
Now lets see an implementation
- Create a New WPF Application
- Open Default MainWindow.xaml.cs
- Add the below code in declaration section of MainWindow.Xaml.CS class
public static RoutedCommand MyCmd = new RoutedCommand();
- Now Implement Executed event
- Then Implement CanExecute: This property will determine whether command can be executed or not. In This case is always set to true
- Now Open MainWindow.XAML and add below code to its Window Tag
- Define a Command binding as shown below
- Create 2 button controls and add the command to both the button as shown below
So both button’s command is bound with same logic. This is simple implementation of commanding in WPF.