2010-08-04 77 views
2

在我以前使用过GetLineFromCharIndex方法的WinForms RichTextBox控件和GetFirstCharIndexOfCurrentLine到光标移到输入文本的制定出起点和终点他目前的路线。如何获取当前行文本从Silverlight 4中RichTextBox控件

我在Silverlight 4中使用新的RichTextBox控件挣扎着,因为看起来没有等效的方法。 GetPositionFromPoint可用,但似乎很笨重。

干杯。

更新...我好歹去使这项工作,但这个要求我使用该控件的选择方法,这种感觉非常错误的...

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

我不认为你可以'不要选择,这是一个正确的方法来做到这一点(“选择”只是一个合理的方式),但你可以避免GetPositionFromPointTextPointer.GetNextInsertionPosition(LogicalDirection):从richTextBox1.Selection.Start开始,并移动到行的开始(char!='\ n')

+0

我的这种方法关注的是,是火灾SelectionChanged事件人为的两倍。为了克服这一点,我需要暂时取消订阅活动用户。丑陋。 – 2010-08-13 11:01:41

1

我需要弄清楚什么时候我在RTB的顶线或底线。为此,我使用了GetCharacterRect方法,然后比较顶部以查看它是否在最后一行或第一行。

您可以这样做,并使用文本指针来移动文本和顶部不匹配的次数。

这里的代码,看看如果光标在第一或最后一行:

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; 
    } 
相关问题