Zsolt
Zsolt

Reputation: 3283

How to retrieve the CaretPosition from the WPF RichTextBox during GotFocus?

I have a TextBox and a RichTextBox with the same text. Everytime I click inside the RichTextBox, the TextBox should be focused with same caret position. My first idea was this:

void richTextBox_GotFocus(object sender, RoutedEventArgs e)
{
     vat textRange = new TextRange(rtfBox.Document.ContentStart, rtfBox.CaretPosition);
     plainTextBox.Focus();
     plainTextBox.CaretIndex = textRange.Text.Length;
}

But the problem is that the RichTextBox doesn't know the CaretPosition in the event handler yet.

Are there any workaround for this?

Maybe with subclassing the RichTextBox?

Upvotes: 1

Views: 491

Answers (1)

a little sheep
a little sheep

Reputation: 1446

If you use Dispatcher.BeginInvoke to run that code it should be called after WPF has finished determining the carets position, etc.

e.g.

private void RichTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    Dispatcher.BeginInvoke(new Action(UpdateTextBoxCaretPosition));
}

void UpdateTextBoxCaretPosition()
{
    var textRange = new TextRange(rtfBox.Document.ContentStart, rtfBox.CaretPosition);
    plainTextBox.Focus();
    plainTextBox.CaretIndex = textRange.Text.Length;
}

Upvotes: 2

Related Questions