GetPositionAtOffset() don't return good position

728 views Asked by At

I use a RichTextBox in WPF (4.0) and I use the GetPositionAtOffset() method to get a text range between two position in the content in RichTextBox.

1) I initialize the text pointer "position" from MyRichTextBox.Document.ContentStart :

TextPointer position = RTBEditor.Document.ContentStart;

2) I get the text from my RichTextBox like that :

var textRun = new TextRange(RTBEditor.Document.ContentStart, RTBEditor.Document.ContentEnd).Text;

3) With Regex I find a string that I want in textRun and get the begin's index and the end's index (I search a text between "/*" and "*/"):

Regex regex = new Regex(@"/\*([^\*/])*\*/");
var match = regex.Match(textRun);
TextPointer start = position.GetPositionAtOffset(matchBegin.Index, LogicalDirection.Forward);
TextPointer end = position.GetPositionAtOffset(matchBegin.Index + matchBegin.Length, LogicalDirection.Backward);

But, when I use these pointers in a textrange and colorize the text inside, it's not the good text matched in my regex (with goods indexes) which is colorized in my RichTextBox.

Why the GetPositionAtOffset() method don't give the position at the index specified ? It's this method the problem or it's somewhere else ?

Thank's for reply, I am stopped in my development.

2

There are 2 answers

0
Sameera Kumarasingha On BEST ANSWER

According to this, https://msdn.microsoft.com/en-us/library/ms598662%28v=vs.110%29.aspx

GetPositionAtOffset returns a TextPointer to the position indicated by the specified offset, in symbols, from the beginning of the current TextPointer.

Any of the following is considered to be a symbol:

  • An opening or closing tag for the TextElement element.

  • A UIElement element contained in an InlineUIContainer or BlockUIContainer. Note that such a UIElement is always counted as exactly one symbol; any additional content or elements contained by the UIElement are not counted as symbols.

  • A 16-bit Unicode character inside of a text Run element.

0
Flo On

Sorry to bother you, the problem was somewhere else.

I initialized the text of my RichTextBox with AppendText() method and not with a paragraph that I added in the blocks. So now it works fine !