c#WPF来自RichTextBox的行号和列号

时间:2013-08-01 12:53:58

标签: c# .net wpf wpf-controls richtextbox

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

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分: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);