来自 RichTextBox 的 c# WPF 行号和列号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17994674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# WPF Line and Column number from RichTextBox
提问by Joseph Little
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.
我正在将一个应用程序从 WinForms 移植到 WPF,并且在尝试获取文本框中所选内容的行号和列号时遇到了障碍。我能够在 WinForms 中非常简单地做到这一点,但 WPF 有一种完全不同的方式来实现 RichTextBox,所以我不知道如何去做。
Here is my WinForms solution
这是我的 WinForms 解决方案
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.
这不适用于 WPF,因为您无法获取当前选择的索引。
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);
回答by Sisco
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.
有几点需要注意。第一行将是第 0 行,因此您可能需要在行号中添加 + 1。此外,如果一行换行其初始列将为 0,但第一行和 CR 之后的任何行都将初始位置列为第 1 列。
回答by marsh-wiggle
To get the real absolute line number (wrapped lines are not counted):
要获得真正的绝对行号(不计算换行数):
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);

