Reputation: 835
Can someone please tell me what is wrong with this. I am trying to get text between several characters before caret and the caret."comparable" is never longer than the actual text in the RichTextBox
.
This is the code that I have:
int coLen = comparable.Length;
TextPointer caretBack = rtb.CaretPosition.GetPositionAtOffset(coLen,
LogicalDirection.Backward);
TextRange rtbText = new TextRange(caretBack, rtb.CaretPosition);
string text = rtbText.Text;
This returns text = ""
Please help!
Upvotes: 0
Views: 2878
Reputation: 3996
This works as expected , I get I a
Piece of code :
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;
EDIT
Here is an MSTest method to explain the behavior of the Caret and reading :
[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");
}
Plus here is a comment from MSDN about the negative index :
offset Type: System.Int32 An offset, in symbols, for which to calculate and return the position. If the offset is negative, the position is calculated in the logical direction opposite of that indicated by the LogicalDirection property.
Upvotes: 4