I am looking for a way to be able to have an event run after a command executes. I am working with EditingCommands (ToggleBold, ToggleItalic…ect.) and would like to be able to have a method called directly after the command finishes whatever it is doing.
An example would be that I have some text selected and press Ctrl+B and that executes EditingCommands.ToggleBold. Right after the text is toggled I want to call an method that will update a ToggleButton that is connected with the selection FontWeight.
I tried using the Executed event but that is unfortunately for me called before the text is affected and consequently updates the button with information that will change in just a second. Does anyone know a way around this?
A workaround is to queue another message in your Executed handler:
This will ensure your work is added to the back of the queue, and will be executed after other messages of the same or higher priority.
However, I’d like to suggest a better solution. If you think about it, the bold button is responsible for executing two different commands: make bold, and make normal. It switches between these two commands based on the currently selected text/caret position. Therefore, you could write a custom
ICommandimplementation that encapsulates two sub-commands (completely untested code):You can then construct a
TogglingCommandwith two commands: one to bolden and one to unbolden text. Then you can bind theButtonin your UI to theActiveCommandproperty to change it in anyway you like based on what will happen when you click the command. For example, if you’re using aToggleButtonyou would bindIsCheckedtoActiveCommandand convert totrueis the active command is unbolden. Of course, the bolden and unbolden commands needCanExecutelogic of their own that inspects the selected text.