WPF .NET 6 RichTextBox获取末尾光标位置设置追加行字体问题
问题:WPF .NET 6中RichTextBox追加文本后选中偏移异常
我基于WPF .NET 6开发了一个包含只读RichTextBox的窗口,用于展示应用可插拔文件的格式化信息。窗口启动时,我通过代码为RichTextBox填充内容:先添加加粗的分类标题,再用小一号的常规字体列出对应文件列表。原本的逻辑是追加文本后选中该内容,再设置Selection Font属性,之前可行,但现在出现问题:每追加一行文本后,选中的内容偏移越来越大。
我推测问题根源在于我的方法仅使用了原始文本,没有考虑RichTextBox中的标记内容,导致字体设置的位置随着行数增加偏差越来越明显。
我尝试了两种方法均未解决问题:
- 自行实现WinForms的
GetFirstCharIndexOfCurrentLine()方法:
public int GetFirstCharIndexOfCurrentLine() { int index = 0; TextRange textRange = new TextRange( Document.ContentStart, Document.ContentEnd ); var alltext = textRange.Text; string[] lines = alltext.Replace("\n", "").Split('\r'); int lineIndex = lines.Length - 1; if (lineIndex > lines.Count()) { throw new ArgumentOutOfRangeException("lineIndex"); } for (int i = 0; i < lineIndex; i++) { index += lines[i].Length; } return index; }
- 通过文本内容选中行:
public void Select(string text) { TextRange textRange = new TextRange(Document.ContentStart, Document.ContentEnd); string alltext = textRange.Text; int index = alltext.IndexOf(text); if (index < 0) { return; } Select(index, text.Length); }
我搜索了各种资料都没找到解决办法,希望能得到帮助。
内容的提问来源于stack exchange,提问作者Jeff Huckins
相关产品推荐
相关产品推荐

