Javidan Guliyev
Javidan Guliyev

Reputation: 227

Is there any chance to raise event when TextBox caret changed?

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?

Upvotes: 5

Views: 8197

Answers (2)

Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

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.

Upvotes: 1

Lukasz M
Lukasz M

Reputation: 5723

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.

Upvotes: 8

Related Questions