【问题标题】:How do get the current line text to cursor from a Silverlight 4 RichTextBox Control如何从 Silverlight 4 RichTextBox 控件获取当前行文本到光标
【发布时间】:2010-08-04 16:13:50
【问题描述】:

在 Winforms RichTextBox 控件中,我之前使用了 GetLineFromCharIndex 方法和 GetFirstCharIndexOfCurrentLine 来计算当前行上键入文本的起点和终点。

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

干杯。

已更新...我已经设法使这项工作但这需要我使用控件的Select方法,这感觉很不对...

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;
}

【问题讨论】:

    标签: silverlight-4.0 richtextbox


    【解决方案1】:

    我认为你不能避免选择,这是一种正确的做法(“选择”只是一个合乎逻辑的选择),但你可以避免 GetPositionFromPointTextPointer.GetNextInsertionPosition(LogicalDirection ):从 @ 开始987654323@ 并移向行首​​ (char != '\n')

    【讨论】:

    • 我担心这种方法会人为地触发两次 SelectionChanged 事件。为了克服这个问题,我需要暂时取消订阅事件订阅者。丑陋。
    【解决方案2】:

    我需要弄清楚我何时处于 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;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多