Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# WPF Line and Column number from RichTextBox

I'm porting an application from WinForms to WPF and I've hit a snag while trying to get the line and column number for where the selection is in the text box. I was able to do it quite simply in WinForms but WPF has a completely different way of implementing a RichTextBox so I have no idea how to go about it.

Here is my WinForms solution

int line = richTextBox.GetLineFromCharIndex(TextBox.SelectionStart);
int column = richTextBox.SelectionStart - TextBox.GetFirstCharIndexFromLine(line);

LineColumnLabel.Text = "Line " + (line + 1) + ", Column " + (column + 1);

This won't work with WPF because you can't get the index of the current selection.

HERE IS THE WORKING SOLUTION:

int lineNumber;
textBox.CaretPosition.GetLineStartPosition(-int.MaxValue, out lineNumber);
int columnNumber = richTextBox.CaretPosition.GetLineStartposition(0).GetOffsetToPosition(richTextBox.CaretPosition);
if (lineNumber == 0)
    columnNumber--;

statusBarLineColumn.Content = string.Format("Line {0}, Column {1}", -lineNumber + 1, columnNumber + 1);
like image 977
Joseph Little Avatar asked Aug 01 '13 12:08

Joseph Little


1 Answers

Something like this may give you a starting point.

TextPointer tp1 = rtb.Selection.Start.GetLineStartPosition(0);
TextPointer tp2 = rtb.Selection.Start;

int column = tp1.GetOffsetToPosition(tp2);

int someBigNumber = int.MaxValue;
int lineMoved, currentLineNumber;
rtb.Selection.Start.GetLineStartPosition(-someBigNumber, out lineMoved);
currentLineNumber = -lineMoved;

LineColumnLabel.Content = "Line: " + currentLineNumber.ToString() + " Column: " + column.ToString();

A couple things to note. The first line will be line 0 so you may want to add a + 1 to the line number. Also if a line wraps its initial column will be 0 but the first line and any line following a CR will list the initial position as column 1.

like image 53
Sisco Avatar answered Oct 21 '22 12:10

Sisco