Reputation: 3283
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
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