当 TextBox 插入符更改时是否有机会引发事件?
我需要在 TextBox 更改时调用一个方法,但 TextBox.Caret
不是 DependencyProperty
,因此无法绑定它。如何知道插入符位置何时发生变化?
I need to call a method when TextBox changes, but TextBox.Caret
isn't a DependencyProperty
, and because of that there is no possibilty to bind it. How to know when the caret position changes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试处理
TextBox
的SelectionChanged
事件。在 XAML 中,您可以这样定义文本框:
接下来,编写处理光标更改的方法:
它会在每次插入符号更改时触发,因此在获得焦点、使用箭头键移动光标、使用鼠标更改光标位置等时触发。
如果您需要在多个文本框中都有这种行为,您也可以基于
TextBox
创建自己的类,并以类似的方式创建自己的事件。我已经在 WPF 项目中对此进行了测试,但它也应该适用于 Silverlight 项目。
You can try to handle
SelectionChanged
event of theTextBox
.In XAML you define your text box like this:
Next, you write method handling the cursor change:
It fires on every caret change, so on getting focus, on moving cursor with arrow keys, on changing cursor position with mouse etc.
If you need this behaviour in several text boxes, you can also just create your own clas based on
TextBox
and create your own event in a similar manner.I've tested this in a WPF project, but it should work in Silverlight project as well.
虽然接受的答案实际上是正确的,但请注意,如果您有一个字母并且从左到右选择它,则
CaretIndex
不会改变:您期望CaretIndex
的值为1
,但您会发现它的值为0
。While the accepted answer is factually correct, please note that
CaretIndex
does not change if, for example, you have a single letter and you select it from left to right: you'd expect theCaretIndex
to have the value1
, but you'll find it has the value0
.