如何在.NET MAUI中获取Editor控件的当前行数?
获取.NET MAUI Editor控件的当前行数
.NET MAUI的Editor控件没有直接提供获取当前行数的API,只能通过SelectionStart拿到光标字符偏移量。要获取行数,分两种场景处理:
1. 仅统计手动换行(硬换行)
如果只需要统计用户手动输入的\n换行,跨平台通用的方法是计算光标前文本中的换行符数量:
var editor = yourEditorInstance; if (editor.SelectionStart >= 0 && !string.IsNullOrEmpty(editor.Text)) { var textBeforeCursor = editor.Text.Substring(0, editor.SelectionStart); // 行数 = 换行符数量 + 1(第一行无换行符) var hardLineCount = textBeforeCursor.Count(c => c == '\n') + 1; }
这种方法简单,但无法识别Editor自动换行(软换行)的情况,适合只关注用户手动换行的场景。
2. 准确获取含自动换行的实际行数
要包含控件自动换行的行数,必须调用各平台的原生控件API,因为自动换行由平台控件的布局逻辑决定。可以封装成扩展方法统一调用:
扩展方法实现
public static class EditorExtensions { public static int GetCurrentLineNumber(this Editor editor) { if (editor == null || string.IsNullOrEmpty(editor.Text) || editor.SelectionStart < 0) return 1; // 兜底:硬换行计数 var textBeforeCursor = editor.Text.Substring(0, editor.SelectionStart); var fallbackLineCount = textBeforeCursor.Count(c => c == '\n') + 1; // 平台特定实现 #if ANDROID var androidEditor = editor.Handler.PlatformView as Android.Widget.EditText; return androidEditor?.GetLineFromOffset(editor.SelectionStart) + 1 ?? fallbackLineCount; #elif IOS var iosEditor = editor.Handler.PlatformView as UIKit.UITextView; if (iosEditor != null) { var cursorPosition = iosEditor.GetPosition(iosEditor.BeginningOfDocument, editor.SelectionStart); if (cursorPosition != null) { var lineRange = iosEditor.GetLineRangeForPosition(cursorPosition); return iosEditor.TextStorage.LineNumberForRange(lineRange) + 1; } } return fallbackLineCount; #elif WINDOWS var windowsEditor = editor.Handler.PlatformView as Microsoft.UI.Xaml.Controls.RichEditBox; if (windowsEditor != null) { windowsEditor.Document.Selection.StartPosition = editor.SelectionStart; return windowsEditor.Document.Selection.GetLineNumber() + 1; } return fallbackLineCount; #else return fallbackLineCount; #endif } }
使用示例
在Editor的点击手势或SelectionChanged事件中调用:
private void OnEditorSelectionChanged(object sender, EventArgs e) { var editor = sender as Editor; var currentLine = editor?.GetCurrentLineNumber() ?? 1; // 处理获取到的行数,比如输出、显示等 }
注意事项
- 确保Editor的
Handler已初始化:控件加载完成后(比如Loaded事件触发后)再调用方法,否则PlatformView会为空。 - 平台API版本:Windows的
GetLineNumber需要Windows App SDK 1.1及以上版本支持。 - 行数计数:各平台原生API返回的行数从0开始,所以需要加1得到从1开始的实际行数。
内容的提问来源于stack exchange,提问作者Jerry Watson
相关产品推荐
相关产品推荐

