从RichTextBox获取部分文本

时间:2011-11-25 20:35:10

标签: c# wpf richtextbox

有人可以告诉我这有什么问题。我试图在插入符号和插入符之前在几个字符之间获取文本。“可比较”永远不会超过RichTextBox中的实际文本。

这是我的代码:

int coLen = comparable.Length;
TextPointer caretBack = rtb.CaretPosition.GetPositionAtOffset(coLen, 
    LogicalDirection.Backward);
TextRange rtbText = new TextRange(caretBack, rtb.CaretPosition);
string text = rtbText.Text;

这会返回text = ""

请帮忙!

1 个答案:

答案 0 :(得分:4)

这可以按预期工作,我得到I a

一段代码:

        RichTextBox rtb = new RichTextBox();
        rtb.AppendText("I am adding some texts to the richTextBox");
        rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;

        int coLen = 3;
        TextPointer caretBack = rtb.CaretPosition.GetPositionAtOffset(-coLen);
        TextRange rtbText = new TextRange(caretBack, rtb.CaretPosition);
        string ttt = rtbText.Text;

修改

这是一个MSTest方法来解释Caret的行为并阅读:

 [TestMethod]
    public void TestRichtTextBox()
    {
        RichTextBox rtb = new RichTextBox();
        rtb.AppendText("I am adding some texts to the richTextBox");

        int offset = 3;

        TextPointer beginningPointer = rtb.CaretPosition.GetPositionAtOffset(offset);
        TextPointer endPointer = rtb.CaretPosition.DocumentEnd;
        TextRange rtbText = new TextRange(beginningPointer, endPointer);

        Assert.IsTrue(rtbText.Text == "m adding some texts to the richTextBox\r\n");

        // Now we if we keep the same beggining offset but we change the end Offset to go backwards.

        beginningPointer = rtb.CaretPosition.GetPositionAtOffset(3);
        endPointer = rtb.CaretPosition; // this one is the beginning of the text
        rtbText = new TextRange(beginningPointer, endPointer);
        Assert.IsTrue(rtbText.Text == "I a");

        // Nowe we want to read from the back three characters.
        // so we set the end Point to DocumentEnd.

        rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
        beginningPointer = rtb.CaretPosition.GetPositionAtOffset(-offset);
        endPointer = rtb.CaretPosition; // we already set this one to the end document
        rtbText = new TextRange(beginningPointer, endPointer);
        Assert.IsTrue(rtbText.Text == "Box");
    }

另外,这里是MSDN关于否定指数的评论:

  

offset类型:System.Int32符号中的偏移量,为   计算并返回位置。如果偏移是负的,那么   位置是在与其相反的逻辑方向上计算的   由LogicalDirection属性指示。