In the previous week’s article, Why Should You use Commands in WPF Applications, we explored the benefits of using commands in the WPF applications. Now that we’ve seen how useful can this be, here is an interesting trick. You can think of a command as a function that is changing or processing an object in a certain way. This object is the parameter of the command. You can also think about the CanExecute result of the function as a signal to terminate the processing chain.
Continuing the previous thought experiment, we can consider a chain of command as being a workflow that processes a certain object.
How would we implement such a command? Given the fact that, the ICommand interface requires us three members to implement, here is what we need to consider.
The CanExecute method of the ICommand interface requires us to tell if the command can be executed with the given parameter. If we are composing commands together, the execution would be only possible from one end of the chain to the other if every command in the chain can be executed with the given parameter.
Since execution of the whole command chain is only possible when all commands can be executed, if any of the commands turns its CanExecute to false, that means the execution value has changed. However, here there is a little trick that we will want to consider. We might be halfway down the execution chain when the first command is turning it’s CanExecute to false. Since we already passed the execution of this command, it will not have any effect on further execution and we want to ignore it during this execution. However, if the currently executed command right after the execution changes its CanExecute to false, that should be a signal to abort the whole execution chain. The reason behind this is that since commands do not know about each other, a command cannot set the execution value of the next one to false to cancel the chain.
The execution of the chain would be done one-by-one in the queue doing the following process.
Verify if the remaining commands are still agreeing that they can be executed.
Execute the first command.
If the command changed its CanExecute to false, abort the execution.
Repeat until there is more command to execute.
In case you think that you would be able to use this command execution pattern nicely in your application, feel free to play with it. I’ve already implemented it; the code is in my git repository at https://github.com/atzimler/Commands. I have also packaged it up with other useful commands that we are going to explore in a NuGet package, which can be found at https://www.nuget.org/packages/ATZ.Commands/. Let’s play Command & Conquer with WPF applications.