[英]WPF RichTextBox PreviewKeyDown and OnTextChange event order differs from normal TextBox
I am having some issues with the WPF RichTextBox
. 我在使用WPF
RichTextBox
时遇到了一些问题。 I have created a behavior which works on both a normal TextBox, and a RichTextBox. 我创建了一个适用于普通TextBox和RichTextBox的行为。 In the behavior, I am using two events:
在行为中,我使用两个事件:
- OnTextChanged - OnTextChanged
- OnPreviewKeyDown - OnPreviewKeyDown
I assumed that OnPreviewKeyDown always fires before OnTextChanged when typing text. 我假设OnPreviewKeyDown在输入文本时总是在OnTextChanged之前触发。
The behavior works like it should for a normal TextBox. 该行为的工作方式与普通TextBox相同。 However, the event order of the WPF RichTextBox's PreviewKeyDown and OnTextChanged seems to differ from the normal TextBox's event order.
但是,WPF RichTextBox的PreviewKeyDown和OnTextChanged的事件顺序似乎与普通TextBox的事件顺序不同。 The following code reproduces the problem by typing "as " very quickly, or even by pressing the 3 keys at the same time:
以下代码通过非常快速地键入“as”或甚至同时按下3个键来重现问题:
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: 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. 基本上问题是我的行为假定普通TextBox的事件顺序。 Obviously, this causes problems when I use the same behavior for a RichTextBox.
显然,当我对RichTextBox使用相同的行为时,这会导致问题。
These two events in certain sense trigger same flow of actions so why not use 这两个事件在某种意义上会触发相同的动作流,所以为什么不使用
protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
{
base.OnPreviewKeyDown(e); // Breakpoint prints the pressed key
}
as a starting point for you logic (since it always fires first), and leave the OnTextChanged alone? 作为逻辑的起点(因为它总是先触发),并单独留下OnTextChanged?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.