开发者

How do get the current line text to cursor from a Silverlight 4 RichTextBox Control

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 equ开发者_开发技巧ivalent 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;
}


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')


I've needed to figure out when I was on the top line or bottom line of the RTB. To do this I used the GetCharacterRect methods then compared the tops to see if it was on the last line or first line.

You could do the same and use a text pointer to move through the text and number of times the tops don't match.

Here's code to see if the cursor is on the first or last lines:

    private bool IsCursorOnFirstLine()
    {
        TextPointer contentStart = this.ContentStart;
        TextPointer selection = this.Selection.End;
        Rect startRect = contentStart.GetCharacterRect(LogicalDirection.Forward);
        Rect endRect = selection.GetCharacterRect(LogicalDirection.Forward);
        return startRect.Top == endRect.Top;
    }

    private bool IsCursorOnLastLine()
    {
        TextPointer start = this.Selection.Start;
        TextPointer end = this.ContentEnd;
        Rect startRect = start.GetCharacterRect(LogicalDirection.Forward);
        Rect endRect = end.GetCharacterRect(LogicalDirection.Backward);
        return startRect.Top == endRect.Top;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜