WPF TextBox Intercepting RoutedUICommands

前端 未结 6 1329
自闭症患者
自闭症患者 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:30

    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;
        }
    }
    

提交回复
热议问题