c#WPF RichTextBox中的行和列编号

本文关键字:编号 RichTextBox c#WPF | 更新日期: 2023-09-27 18:25:52

我正在将一个应用程序从WinForms移植到WPF,在试图获取文本框中所选内容的行号和列号时遇到了一个障碍。我可以在WinForms中简单地完成它,但WPF有一种完全不同的方式来实现RichTextBox,所以我不知道如何进行

这是我的WinForms解决方案

int line = richTextBox.GetLineFromCharIndex(TextBox.SelectionStart);
int column = richTextBox.SelectionStart - TextBox.GetFirstCharIndexFromLine(line);
LineColumnLabel.Text = "Line " + (line + 1) + ", Column " + (column + 1);

这将不适用于WPF,因为您无法获得当前所选内容的索引。

以下是有效的解决方案:

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);

c#WPF RichTextBox中的行和列编号

这样的事情可能会给你一个起点。

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();

有几点需要注意。第一行将是第0行,因此您可能需要在行号中添加+1。此外,如果一行换行,其初始列将为0,但第一行和CR后面的任何一行都将初始位置列为列1。

要获得真正的绝对行数(换行不计算在内):

Paragraph currentParagraph = rtb.CaretPosition.Paragraph;
// the text becomes either currently selected and the selection reachted the end of the text or the text does not contain any data at all
if (currentParagraph == null)
{
    currentParagraph = rtb.Document.ContentEnd.Paragraph;
}
lineIndexAbsolute = Math.Max(rtb.Document.Blocks.IndexOf(currentParagraph), 0);