Can you explain WPF command with an example?

Answer

When end users interact with application they send actions like button click, 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.

public class IncrementCounter : System.Windows.Input.ICommand
    {
        private clsCounter obj;
        public IncrementCounter(clsCounter o)
        {
            obj = o;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            obj.Increment();
        }
    }

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.

<Button Command="{Binding IncrementClick, Source={StaticResource Counterobj}}"/>

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.

All wpf Questions

Ask your interview questions on wpf

Write Your comment or Questions if you want the answers on wpf from wpf Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---