I am trying to get Undo/Redo keyboard shortcuts working in my WPF application (I have my own custom functionality implemented using the Command Pattern). It seems, however, tha
If you want to implement your own Undo/Redo and prevent the TextBox from intercepting, attach to the command preview events through CommandManager.AddPreviewCanExecuteHandler
and CommandManager.AddPreviewExecutedHandler
and set the event.Handled flag to true:
MySomething()
{
CommandManager.AddPreviewCanExecuteHandler(
this,
new CanExecuteRoutedEventHandler(OnPreviewCanExecuteHandler));
CommandManager.AddPreviewExecutedHandler(
this,
new ExecutedRoutedEventHandler(OnPreviewExecutedEvent));
}
void OnPreviewCanExecuteHandler(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Undo)
{
e.CanExecute = true;
e.Handled = true;
}
else if (e.Command == ApplicationCommands.Redo)
{
e.CanExecute = true;
e.Handled = true;
}
}
void OnPreviewExecutedEvent(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Undo)
{
// DO YOUR UNDO HERE
e.Handled = true;
}
else if (e.Command == ApplicationCommands.Redo)
{
// DO YOUR REDO HERE
e.Handled = true;
}
}