Heavy WPF Commands – Part I

Recently, I had a conversation about how much logic a WPF command in .NET might provide and how few implementation it should contain. Basically, this conversation was triggered by different understanding of the semantics of WPF commands. I realized that there is a lot misunderstanding how to implement and use commands in WPF that causes trouble in understanding the program flow and hard to maintain code in the long term. Therefore, I decided this is definitely worth some research on WPF commands and their usage. This is the first articles in a series, I will focus on the usage of WPF commands, their meaning, various implementations and best practices.

The intention of commands are pretty clear described in the Commanding Overview MSDN article:

The first purpose is to separate the semantics and the object that invokes a command from the logic that executes the command.

Therefore, commands allow you to reuse parts of your application logic for different targets of of application while separating this logic from the actual user experience (UIX). Regardless whether implementing the logic using the code behind approach in WPF with RoutedCommands, following the MVVM pattern using RelayCommands or building composite applications using DelegateCommands and CompositeCommands, the concept behind commands stays always the same.

All this is made possible by the ICommand interface with its two method declarations CanExecute and Execute. Basically, this allows your UIX to ask if a certain action can be performed and of course to trigger this action. The one who asks for this is called command source. If the command tells it cannot execute this action, is usually disables itself.

The Idea behind WPF Commands

Which logic to perform is not within the concern of the command source. The command maps the “Do Something” call from the command source to the actual logic and invokes this logic on behalf of the command source. Consequently, the logic to be invoked should not be implemented at an instance of the command itself. Any command serves simply as a protocol between application logic and UIX and allows you to separate both from each other.

In a following articles, I will focus on various best practices how to implement commands before having a look in the different possibilities how to use them in common WPF as well as in composite applications.

Leave a Reply