WPF Commands Explained

By | June 22, 2015

WPF has many delightful features. Commands are one of them. Somehow they have remind me of pointers in C and Delegates and Events in C#. If you want to know more about WPF custom command implementation which takes parameters then refer to this blog post.

However if I were you, I would simply stop here and use FODY Commander instead. It is much better. Trust me. But in case you love pain, read on.

As always, in this WPF commands example, I will deal with the “WHY” first and then the “HOW”.

WHY WPF COMMANDS

What do you do when you want to execute some code when a button is clicked?
You write an event handler for this action and put the code inside it.

In your XAML:

<Button Content="Button" Click="OnClick"/>

And in code behind:

private void OnClick(object sender, RoutedEventArgs e)
{
    //Some twisted logic
}

What if we are talking of some generic action? Like Save?
As you must be aware, Cntrl+S or Menu->File->Save or Right Click->Save, all three do the same thing. Save something. Three different actions but same end result.

In other words, the logic which gets executed in the end is the same. But it has to be put in three different event handlers, one for each action. The same logic. Three different places. Not right.

Commands make it simpler. You associate these actions with a single command. Command will be linked a single event handler. Which will contain the logic.

Wait. Actions?
I mean the controls like Button, CheckBox, MenuItem etc. In short any control which implements <ICommandSource> Interface.

So this settles the question of WHY commands. In a broad general way. You can always go through the details. And there are quite a bit of them to be honest.

HOW TO USE WPF COMMANDS
WPF designers knew that commands will be needed and provided a set of implementations for commands. Commands which address some common needs. Full list has been provided in this answer on StackOverflow. God Bless them. If you want to do a custom command implementation then check out the post I will be putting soon.

Let us have brief look how you will go about using pre-implemented command.
We will use the ApplicationCommands.New command to illustrate.

In the XAML we have:

<Button Content="Button" Command="ApplicationCommands.New"/>

Notice the Click is gone. We do not need it. We will put the logic in the handler which is linked with command. And not the event handler for the button click. Hence removed.

You have to define the Commandbindinding.
But before that lets clear up some terminology. Enough of command word floating around.

Command: This represents, well a command to do something. Like “Release the Kraken“.
Command Source: The command is linked to a control. Like Button. When you click the button, command gets executed.
Command Bindings: This is the glue which links the command to the function which will get run when the command is executed.

So now on to commandbindings. You can do them in XAML like this:

<Window x:Class="Commands.TestNewCommand"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow">
<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.New"
    Executed="Command_Executed" CanExecute="Command_CanExecute"></CommandBinding>
</Window.CommandBindings>

Or in the Code behind:

CommandBinding binding = new CommandBinding(ApplicationCommands.New);
binding.CanExecute += Command_CanExecute;
binding.Executed += Command_Executed;
CommandBindings.Add(binding);

In both the cases you have to provide the implementation of the two methods: Command_CanExecute and Command_Executed.
For example:

private void Command_Executed(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Hello there");
    //You can put any logic here
}

private void Command_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    //You can put some logic here to make e.CanExecute true or false
    e.CanExecute = true;
}

(And I came up with these names. You can name them anything you want. But this is the usual way they are named)

Command_Executed is straight forward. It has all the action packed in it.

What about “Command_CanExecute” method? This method is the place where you put the logic to enable or disable to control.
A real world example will be the Login Button. You do not want it to be enabled when there is nothing in the User name and Password field.
Also you might want to keep it disabled while the authentication is going on. In this sample I hardcoded it to “true” to keep the button enabled.

Got Command? Check.
Got Command bindings sorted? Check

Time to now link the command with the Button. This XAML does the trick.

<Grid>
	<Button Content="Button"
			Command="ApplicationCommands.New"
			HorizontalAlignment="Left" Margin="219,96,0,0" VerticalAlignment="Top" Width="75" />
</Grid>

Now as you can see there is not much difference between this rather lengthy code sample and a simple button click event handler. You clicked button and a message box came up. Big deal. Right?

To appreciate the stuff now add a checkbox.

<Grid>
	<Button Content="Button"
			Command="ApplicationCommands.New"
			HorizontalAlignment="Left" Margin="219,96,0,0" VerticalAlignment="Top" Width="75" />
	<CheckBox Content="CheckBox"
			Command="ApplicationCommands.New"
			HorizontalAlignment="Left" Margin="254,195,0,0" VerticalAlignment="Top" />
</Grid>

See how we are now reusing the command. On clicking in the checkbox, you see the same message box. Why? Because the same code was executed. The code linked to the command.
And this is where the power lies. Configure a command and then use it with many controls.

As I said earlier, this is a simple example to set you off on the slippery slope of WPF commands. A thorough understanding will entail a long walk in the Garden of ICommand interface, RoutedCommand Class, RoutedUICommand Class, ICommandSource interface and counting.

This small WPF command tutorial was on how to use the commands provided my WPF designers.
What if you want to have MySuperAwesomeCommand of your own?
Implementing WPF custom commands will be subject of another blog post is discussed in this blog post.

One thought on “WPF Commands Explained

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.