8

我正在将应用程序从 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);
4

2 回答 2

8

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

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 列。

于 2013-08-01T13:31:07.030 回答
0

要获得真正的绝对行号(不计算环绕行):

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);
于 2019-03-23T17:07:55.180 回答