views:

65

answers:

1

In the Winforms RichTextBox control I have previously used the GetLineFromCharIndex method and the GetFirstCharIndexOfCurrentLine to work out the start and end points of the typed text on he current line.

I am struggling with the new RichTextBox control in Silverlight 4 as there doesn't appear to be equivalent methods. GetPositionFromPoint is available but seems a but clunky.

Cheers.

Updated...I have gone someway to making this work but this requires me to use the Select method of the control, this feels very wrong...

private string GetCurrentLine()
{
    TextPointer prevSelStart = richTextBox1.Selection.Start;
    Point lineStart = new Point(0, prevSelStart.GetCharacterRect(LogicalDirection.Forward).Y);
    TextPointer prevSelEnd = richTextBox1.Selection.End;
    TextPointer currentLineStart = richTextBox1.GetPositionFromPoint(lineStart);

    //need to find a way to get the text between two textpointers
    //other than performing a temporary selection in the rtb
    richTextBox1.Selection.Select(currentLineStart, prevSelStart);
    string text = richTextBox1.Selection.Text;
    //revert back to previous selection
    richTextBox1.Selection.Select(prevSelStart, prevSelEnd);

    return text;
}
+1  A: 

I don't think you can't avoid the selection, it's a proper way to do it (the "selection" is just a logical one), but you can avoid GetPositionFromPoint with TextPointer.GetNextInsertionPosition(LogicalDirection ): Start from richTextBox1.Selection.Start and move towards the beginning of the line (char != '\n')

Samuel_xL
My concern with this approach is that is fires the SelectionChanged event twice artificially. To overcome this I need to unsubscribe the event subscribers temporarily. Ugly.
Jon Simpson