The workaround is the next message queue in the Executed handler:
void copy_Executed(object sender, EventArgs e) { Dispatcher.BeginInvoke(new ThreadStart(delegate() {
This will ensure that your work is added to the back of the queue and will be executed after other messages with the same or higher priority.
However, I would like to offer a better solution. If you thought about it, the bold button is responsible for executing two different commands: make it bold and make it normal. It switches between the two teams based on the currently selected text / caret position. Therefore, you can write a custom implementation of ICommand that encapsulates two subcommands (completely untested code):
public class TogglingCommand : ICommand { private readonly ICommand _command1; private readonly ICommand _command2; private ICommand _activeCommand; public TogglingCommand(ICommand command1, ICommand command2) { _command1 = command1; _command2 = command2; } public ICommand ActiveCommand { get { return _activeCommand; } } public bool CanExecute(object parameter) { if (_command1.CanExecute(parameter)) { _activeCommand = _command1; } else if (_command2.CanExecute(parameter)) { _activeCommand = _command2; } else { _activeCommand = null; } return _activeCommand != null; } public void Execute(object parameter) { _activeCommand.Execute(parameter); } }
Then you can build a TogglingCommand with two commands: one for bolden and one for unlocking text. You can then bind Button in your user interface to the ActiveCommand property to change it anyway based on what happens when you press the command. For example, if you use ToggleButton , you must bind IsChecked to ActiveCommand and convert the active unbolden command to true. Of course, the bolden and unbolden commands need their own CanExecute logic, which checks the selected text.
source share