Commands In WPF – Part IV


In Part III of this article series; we have seen how Input Binding is helpful. In this article we will explore on Command Objects and Command Types.

Command Objects

A Command Object identifies a particular Command. It doesn’t know how to handle the Command; as we have seen that is the job of Command Binding.

Command Objects are typically made available through static properties. Such as ApplicationCommands.Properties

There are several places from which you can get hold of a Command Object.

Some Controls define commands. For Example: the Scrollbar Control defines one for each of its actions, and makes these available in static fields.

Such as LineUpCommand, PageDownCommand.

However, most commands are not unique to a particular control.

Some are related to application level actions such as: “New File” or “Open”.

WPF provides a set of classes that define standard commands. Such as follows:

Although the standard commands cover a lot of the common features found in many applications, applications usually have functionality of their own not addressed by the standard commands. We can use the command system for application-specific actions by defining custom commands.


Application Commands

Earlier we have seen how to use Copy, Cut and Paste Commands in WPF. The Clipboard Commands are part of ApplicationCommands.

We will explore more on ApplicationCommands Commands, such as: Open.

So let’s have two Button saying caption as Open and a TextBox to display the file content.

As you see above we have the Button and TextBox placed.

Now let’s add the Command.

As you see in the above XAML display we have two events such as Executed and CanExecute. These events are Command specific events to be handled to execute the command.

So lets handle the command.

We have to handle the CanExecute to True otherwise the Command would not be handled.

Now in the Executed event handler we can write our code to execute.

As you see in above code display, I have opened a file dialog to open the Text Files.

Now let’s run the application.

As soon as you click on the Open button the Command would get executed and we would have the Open File Dialog Box.

After opening the file:

So we have successfully used the Open Command.

Hope this article helps.