简体   繁体   English

WPF:如何从 TextBox 获取当前绝对行号和列号(忽略文本换行)

[英]WPF: How to get current absolute line and column numbers from TextBox (ignoring text wrapping)

I am trying to get the absolute position of the line and column/character of caret in TextBox (like it implemented in Windows notepad).我正在尝试获取 TextBox 中插入符号的行和列/字符的绝对 position(就像它在 Windows 记事本中实现的那样)。 I know about TextBox.GetLineIndexFromCharacterIndex() or TextBox.GetCharacterIndexFromLineIndex() , but those methods returns relative postion (I mean that this methods counts wrapped lines) and for example if first line wraps to second line, this method will return index of second line, so I need another solution for this.我知道TextBox.GetLineIndexFromCharacterIndex()TextBox.GetCharacterIndexFromLineIndex() ,但这些方法返回相对位置(我的意思是这个方法计算换行数),例如,如果第一行换行到第二行,这个方法将返回第二行的索引,所以我需要另一种解决方案。 Also I tried calculate position by myself (using loop through the string) but with large amount of text it works very slowly.我还尝试自己计算 position (使用循环遍历字符串),但是对于大量文本,它的工作速度非常慢。

Text without wrapping Text with wrapping没有换行的文本 有换行的文本

I don't think there's any way you'll be able to get the line number of a given offset (character) without looping through the text in some way.我认为没有任何方法可以在不以某种方式循环文本的情况下获得给定偏移量(字符)的行号。 However, some methods will be more efficient than others.但是,有些方法会比其他方法更有效。

You can take some inspiration from the TextBox control itself, since the source code is freely available here:您可以从TextBox控件本身获得一些灵感,因为源代码可在此处免费获得:
https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/windows/Controls/TextBox.cs https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/windows/Controls/TextBox.cs

The TextBox needs to enumerate over every character anyway in order to display the text. TextBox无论如何都需要枚举每个字符才能显示文本。 As part of that process it also needs to decide when to start new lines.作为该过程的一部分,它还需要决定何时开始新生产线。 To make future calculations faster, it keeps an internal list of "line metrics"- basically a list of where each line starts and how long each line is.为了使未来的计算更快,它保留了一个“行度量”的内部列表——基本上是每行从哪里开始以及每行有多长的列表。 It uses this internal list to do calculations like GetCharacterIndexFromLineIndex and GetLineIndexFromCharacterIndex more efficiently, without having to go through each character again.它使用此内部列表更有效地执行GetCharacterIndexFromLineIndexGetLineIndexFromCharacterIndex等计算,而无需再次通过每个字符 go。

You should be able to do something similar.你应该能够做类似的事情。 Make your own list of line positions at the start by looping through the text in the background when it's first loaded, then keep that list up to date as changes are made.在第一次加载时循环浏览背景中的文本,在开始时制作您自己的行位置列表,然后在进行更改时使该列表保持最新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM