The order of the WPF RichTextBox PreviewKeyDown and OnTextChange events is different from the usual TextBox

I'm having some problems with WPF RichTextBox. I created a behavior that works with both regular TextBox and RichTextBox. I use two events in the behavior:
- OnTextChanged
- OnPreviewKeyDown

I assumed that OnPreviewKeyDown always fires before OnTextChanged when entering text.

The behavior works the same as for a regular TextBox. However, the order of the WPF RichTextBox PreviewKeyDown and OnTextChanged events is different from the usual order of TextBox events. The following code reproduces the problem by typing “how” very quickly or even by pressing 3 keys simultaneously:

Textbox

class TestTextBox : TextBox
{
    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        base.OnTextChanged(e); // Breakpoint prints "TextChanged!"
    }

    protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
    {
        base.OnPreviewKeyDown(e); // Breakpoint prints the pressed key
    }
}

Output:
A
TextChanged!
S
TextChanged!
Space
TextChanged!

RichTextBox:

class TestRichTextBox : RichTextBox
{
    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        base.OnTextChanged(e); // Breakpoint prints "TextChanged!"
    }

    protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
    {
        base.OnPreviewKeyDown(e); // Breakpoint prints the pressed key
    }
}

Output:
A
S
Space
TextChanged
TextChanged
TextChanged

, eventorder TextBox. , , RichTextBox.

  • RichTextBox ?
  • TextBox ?
  • - ?
+4
1

,

protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
{
    base.OnPreviewKeyDown(e); // Breakpoint prints the pressed key
}

( ) OnTextChanged ?

0

Source: https://habr.com/ru/post/1533869/


All Articles