2011-11-25 110 views
0

有人可以告诉我这有什么问题。我试图在脱字符和脱字符之前在几个字符之间得到文本。“可比”不会超过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 = ""

请帮帮忙!

回答

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的方法来解释符的行为和阅读:

[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的负面指标注释:

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

+0

Thanks for input.I should be getting“Box”because I need it to backwords from the end where the caret is。我希望它在脱字符前得到文本 – gumenimeda

+0

检查我的编辑,如果你想后退,你需要设置CaretPosition结束文档。看起来后退不起作用,但是做-coLen有帮助。 – MBen

+0

非常感谢!我花了很多时间研究这个! – gumenimeda