The command pattern is old in the software industry. The earliest date that I’ve found that it was published is in the Design Patterns book, by the “Gang of Four”, which was first published in 1994. Most likely it was around earlier, otherwise would not make the book. While it is a well-known pattern, the WPF command pattern is slightly different. You can try to use it in the same way as in the book, but it strengths comes from the fact that it integrates well with the WPF controls if you implement your commands properly. As an illustration, let’s have an example and in later articles we can dive into some more interesting scenarios that I’ve found useful. The source code for this article in a complete solution can be found on my github page in the WpfWednesday repository under the project Z12_Commands.
The example will be a menu on a WPF application which will display a message in a dialog box. There will be also a button, that we can press and that will enable or disable the menu item.
Let’s see first the Window.
As you can see, nothing extra we added all components to XAML. The only interesting thing here is that the Command property of the MenuItem is attached to a static command variable. In the code behind file of the MainWindow we are going to handle the click event of the button in Button_Click, which is only going to set the result for what the TestCommand should return as return value when the CanExecute function is called on it.
That’s it. It is really it. The rest is the command and implementing the ICommand interface correctly will disable and enable the associated menu depending if the command can execute or not. This makes constructing user interfaces in state machine fashion easy.
So, what this command does? Well, it displays a message box with a message in its Execute method. The get part of the WhatShouldWeReturnForCanExecute property is evident, it is returning the value of the property from the background storage variable. The trick is in the set part of the property. If we try to set to the same value as it is already nothing happens. This is the expected behavior from all property implementations, you should not fire extra events, costly actions might be associated with them, like querying an SQL database for hundred thousand records. Be aware of this. However, when we can the value we also raise the CanExecuteChanged event. WPF controls capable of handling commands are listening for this event and they will check if the command can execute with the associated parameter of the control. This associated parameter can be set through the control’s CommandParameter property, which we will not use for now. If the command reports to the control that it cannot execute, the control will simply disable its own action, so the user will not have the chance to initiate the command execution. Try it out, it will make your life easy implementing user interfaces.