Using GetLineStartPosition to Get End of Line in WPF RichTextBox

A bit of background. I would like to be able to process the text for the line that the caret is in in WPF RichTextBox. See my previous question about the TextPointer class: How to track a TextPointer in a WPF RichTextBox? .

I know how to get TextPointer at the beginning of the current line using GetLineStartPosition with 0 as an argument, but now I would like to get TextPointer at the end of the line. In my previous question, it was suggested that this is possible using the GetLineStartPosition method.

I would appreciate it if someone could explain a little how GetLineStartPosition works with respect to end-of-line pointers.

Thanks in advance for your help.

+4
c # wpf richtextbox
source share
2 answers

GetLineStartPosition can return you the beginning of a line, but not the end of a line. To do this, you will have to combine it with GetInsertionPosition .

Here's GetLineStartPosition works:

  • GetLineStartPosition(-1) gets the beginning of the previous line
  • GetLineStartPosition(0) gets the beginning of the current line
  • GetLineStartPosition(1) gets the start of the next line

You can also call it with large integers to get the lines further.

To get the end of a line, simply start the beginning of the next line, then get the previous insertion position. Mainly:

 pointer.GetLineStartPosition(1).GetInsertionPosition(LogicalDirection.Backward); 

However, this does not work when you are on the last line of the document: GetLineStartPosition returns null.

Easy way to fix this:

 var nextStart = pointer.GetLineStartPosition(1) var lineEnd = (nextStart !=null ? nextStart : pointer.DocumentEnd).GetInsertionPosition(LogicalDirection.Backward); 

You must use the GetInsertionPosition argument, and not just move a single character using GetNextContextPosition or GetPointerAtOffset in that each element in the FlowDocument element tree is a symbol. For example, if your current row is the last row in the table, GetLineStartPosition(1) will return the pointer inside the first run in the first paragraph following the table, while the end of the current row is the end of the last run in the last paragraph in the last TableCell, .. . you get the idea.

It is best to allow WPF the complexity of moving TextPointers around a FlowDocument , which means using GetInsertionPosition to find the end of the same line that the original TextPointer .

+11
source share

The end of the current line coincides with the beginning of the next line, so you can use GetLineStartPosition(1) . Note that this will return null when you are on the last line, so you can use a DocumentEnd in this case.

 var currentLine = new TextRange(rtb.CaretPosition.GetLineStartPosition(0), rtb.CaretPosition.GetLineStartPosition(1) ?? rtb.CaretPosition.DocumentEnd).Text; 
+2
source share

All Articles