【问题标题】:c# WPF Line and Column number from RichTextBoxc# 来自 RichTextBox 的 WPF 行号和列号
【发布时间】:2013-08-02 09:54:05
【问题描述】:

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

【问题讨论】:

  • 你有没有尝试过,告诉你它是如何完全不同的?
  • 您需要查找依赖关系,但这不是一件容易的事。我确实对此进行了调查,看到需要做多少工作(或者至少我需要学习多少)并更改了我的产品规格,这样我就可以避免它!如果时间对您的项目至关重要,您最好寻找第三方。
  • 用我的 WinForms 解决方案更新了@Will 我可以从框中获取文本但我无法获得选择器的位置,而且我必须计算出它通过了多少行/列戴夫真可惜:(

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


【解决方案1】:

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

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,我必须做一件小事,即从列中减去 1。我将发布我的工作解决方案
【解决方案2】:

获取真正的绝对行号(不计算换行):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    相关资源
    最近更新 更多