我在使用 WPF RichTextBox
时遇到一些问题。我创建了一种适用于普通文本框和 RichTextBox 的行为。在行为中,我使用了两个事件:
- OnTextChanged
- OnPreviewKeyDown
我假设在键入文本时 OnPreviewKeyDown 总是在 OnTextChanged 之前触发。
该行为与普通 TextBox 应有的行为一样。但是,WPF RichTextBox 的 PreviewKeyDown 和 OnTextChanged 的事件顺序似乎与普通 TextBox 的事件顺序不同。 以下代码通过快速键入“as”或什至同时按下 3 个键来重现该问题:
文本框
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!
富文本框:
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
基本上,问题是我的行为假定了普通 TextBox 的事件顺序。显然,当我对 RichTextBox 使用相同的行为时,这会导致问题。
- 为什么第一个 RichTextBox 的事件顺序不同 地点?
- 普通 TextBox 的事件顺序是否也不同于 假定顺序?
- 我能以某种方式强制事件顺序,或者在某些情况下达到相同的结果吗? 其他方式?
最佳答案
这两个事件在某种意义上触发相同的 Action 流程,所以为什么不使用
protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
{
base.OnPreviewKeyDown(e); // Breakpoint prints the pressed key
}
作为您逻辑的起点(因为它总是先触发),并单独留下 OnTextChanged?
关于c# - WPF RichTextBox PreviewKeyDown 和 OnTextChange 事件顺序与普通 TextBox 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22707596/