当 TextBox 插入符更改时是否有机会引发事件?

发布于 2024-12-23 08:19:19 字数 118 浏览 4 评论 0原文

我需要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若水般的淡然安静女子 2024-12-30 08:19:19

您可以尝试处理TextBoxSelectionChanged事件。

在 XAML 中,您可以这样定义文本框:

<TextBox x:Name="myTextBox" SelectionChanged="TextBox_SelectionChanged" />

接下来,编写处理光标更改的方法:

private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    int caretPosition = myTextBox.CaretIndex;

    //put your handling code here...
}

它会在每次插入符号更改时触发,因此在获得焦点、使用箭头键移动光标、使用鼠标更改光标位置等时触发。

如果您需要在多个文本框中都有这种行为,您也可以基于 TextBox 创建自己的类,并以类似的方式创建自己的事件。

我已经在 WPF 项目中对此进行了测试,但它也应该适用于 Silverlight 项目。

You can try to handle SelectionChanged event of the TextBox.

In XAML you define your text box like this:

<TextBox x:Name="myTextBox" SelectionChanged="TextBox_SelectionChanged" />

Next, you write method handling the cursor change:

private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    int caretPosition = myTextBox.CaretIndex;

    //put your handling code here...
}

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.

狼亦尘 2024-12-30 08:19:19

虽然接受的答案实际上是正确的,但请注意,如果您有一个字母并且从左到右选择它,则 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 the CaretIndex to have the value 1, but you'll find it has the value 0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文