Now for the answer to the main WPF interview question.
When end users interact with application they send actions like right click , control + c, control + v etc. A command class in WPF wraps these end user actions in to a class so that they can be reused again and again.
WPF Command class idea is an implementation of command pattern from gang of four design pattern.
To create a command class we need to implement the “ICommand” interface. For example below is a simple command class which increments a counter class by calling “Increment” method.
The command class needs two implement two methods as shown in the above code:-
What to Execute (Execute) – Command class is all about wrapping actions of end users so that we can reuse them. At the end of the day Action invokes methods. Mean for instance a “btnmaths_click” action will invoke “Add” method of a class. The first thing we need to specify in the command class is which method you want to execute. In this case we want to call the “Increment” method of “clsCounter” class.
When to execute (CanExecute) – The second thing we need to specify is when the command can execute, means validations. This validation logic is specified in the “CanExecute” function. If the validation returns true then “Execute” fires or else the action has no effect.
You can see the code of “CanExecute” and “Execute” in the above code snippet.
Once you have created the “Command” class you can bind this with the button using the “Command” property as shown in the below XAML code.”CounterObj” is a resource object.
So now that the action is wrapped in to command we do not need to write method invocation code again and again in behind code, we just need to bind the command object with the WPF UI controls wherever necessary.
Below video explain what is WPF and how they differ from Windows form