I am having some issues with the WPF RichTextBox
. I have created a behavior which works on both a normal TextBox, and a RichTextBox. In the behavior, I am using two events:
- OnTextChanged
- OnPreviewKeyDown
I assumed that OnPreviewKeyDown always fires before OnTextChanged when typing text.
The behavior works like it should for a normal TextBox. However, the event order of the WPF RichTextBox's PreviewKeyDown and OnTextChanged seems to differ from the normal TextBox's event order. The following code reproduces the problem by typing "as " very quickly, or even by pressing the 3 keys at the same time:
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
Basically the problem is that my behavior assumes the eventorder of the normal TextBox. Obviously, this causes problems when I use the same behavior for a RichTextBox.
- Why does the event order differ for the RichTextBox in the first place?
- Could the event order of the normal TextBox also differ from the assumed order?
- Can I somehow force the event order, or reach the same result in some other way?