WPF TextBox Intercepting RoutedUICommands

前端 未结 6 1454
自闭症患者
自闭症患者 2021-02-14 03:10

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

6条回答
  •  不要未来只要你来
    2021-02-14 03:46

    There is no straightforward way to supress all bindings, do not set IsUndoEnabled to false as it will only trap and flush Ctrl + Z key binding. You need to redirect CanUndo, CanRedo, Undo and Redo. Here is how I do it with my UndoServiceActions singleton.

    textBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo,
                                                   UndoCommand, CanUndoCommand));
    textBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo,
                                                   RedoCommand, CanRedoCommand));
    
    private void CanRedoCommand(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = UndoServiceActions.obj.UndoService.CanRedo;
        e.Handled = true;
    }
    
    private void CanUndoCommand(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = UndoServiceActions.obj.UndoService.CanUndo;
        e.Handled = true;
    }
    
    private void RedoCommand(object sender, ExecutedRoutedEventArgs e)
    {
        UndoServiceActions.obj.UndoService.Redo();
        e.Handled = true;
    }
    
    private void UndoCommand(object sender, ExecutedRoutedEventArgs e)
    {
        UndoServiceActions.obj.UndoService.Undo();
        e.Handled = true;
    }
    

提交回复
热议问题