How to keep track of TextPointer in WPF RichTextBox?

Posted by Alan Spark on Stack Overflow See other posts from Stack Overflow or by Alan Spark
Published on 2010-06-15T14:35:30Z Indexed on 2010/06/15 18:32 UTC
Read the original article Hit count: 689

Filed under:
|
|

I'm trying to get my head around the TextPointer class in a WPF RichTextBox.

I would like to be able to keep track of them so that I can associate information with areas in the text.

I am currently working with a very simple example to try and figure out what is going on. In the PreviewKeyDown event I am storing the caret position and then in the PreviewKeyUp event I am creating a TextRange based on the before and after caret positions. Here is a code sample that illustrates what I am trying to do:

// The caret position before typing
private TextPointer caretBefore = null;

private void rtbTest_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // Store caret position
    caretBefore = rtbTest.CaretPosition;
}

private void rtbTest_PreviewKeyUp(object sender, KeyEventArgs e)
{
    // Get text between before and after caret positions
    TextRange tr = new TextRange(caretBefore, rtbTest.CaretPosition);
    MessageBox.Show(tr.Text);
}

The problem is that the text that I get is blank. For example, if I type the character 'a' then I would expect to find the text "a" in the TextRange.

Does anyone know what is going wrong? It could be something very simple but I've spent an afternoon getting nowhere.

I am trying to embrace the new WPF technology but find that the RichTextBox in particular is so complicated that it makes even doing simple things like this difficult. If anyone has any links that do a good job of explaining the TextPointer, I would appreciate it if you can let me know.

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf