You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui中Editor控件如何触发Completed事件?

解决.NET Maui Editor在Android上既保留换行又触发Completed事件的问题

在Android平台上,Editor默认按下回车键是换行,而Completed事件需要触发的话,得让键盘显示完成按钮——用户点击这个按钮就能触发Completed,同时回车键依然保留换行功能,下面是两种可行方案:

方案一:通过XAML配置自定义键盘

直接在XAML里给Editor指定带有“完成”按钮的键盘,Android键盘会自动显示完成按钮,点击即可触发Completed事件:

<Editor Grid.Row="1" 
        x:Name="SurveyCodes"
        FontSize="20"
        TextColor="Yellow"
        Placeholder="Enter survey codes"
        Completed="SurveyCodesCompleted"
        TextTransform="Uppercase">
    <Editor.Keyboard>
        <Keyboard x:FactoryMethod="Create">
            <x:Arguments>
                <KeyboardFlags>None</KeyboardFlags>
                <ReturnType>Done</ReturnType>
            </x:Arguments>
        </Keyboard>
    </Editor.Keyboard>
</Editor>

这里通过Keyboard.Create方法指定ReturnType="Done",让Android键盘底部显示“完成”按钮,点击该按钮就会触发你写的SurveyCodesCompleted方法,回车键依然用来换行。

方案二:自定义Android平台Handler(更灵活)

如果方案一不满足需求,可以通过自定义Handler强制给Android的EditText添加完成按钮并监听事件:

  1. 在Android项目中创建自定义Handler类:
using Microsoft.Maui.Handlers;
using Android.Widget;
using Android.Views.InputMethods;

namespace YourAppNamespace.Platforms.Android;

public class CustomEditorHandler : EditorHandler
{
    protected override void ConnectHandler(EditText platformView)
    {
        base.ConnectHandler(platformView);
        // 设置输入法选项为“完成”
        platformView.ImeOptions = ImeAction.Done;
        platformView.SetImeActionLabel("完成", ImeAction.Done);
        // 绑定EditorAction事件
        platformView.EditorAction += PlatformView_EditorAction;
    }

    private void PlatformView_EditorAction(object sender, TextView.EditorActionEventArgs e)
    {
        if (e.ActionId == ImeAction.Done)
        {
            // 触发Completed事件
            VirtualView.Completed?.Invoke(VirtualView, EventArgs.Empty);
            // 隐藏键盘
            var imm = (InputMethodManager)Context.GetSystemService(Android.Content.Context.InputMethodService);
            imm.HideSoftInputFromWindow(PlatformView.WindowToken, HideSoftInputFlags.None);
        }
    }

    protected override void DisconnectHandler(EditText platformView)
    {
        platformView.EditorAction -= PlatformView_EditorAction;
        base.DisconnectHandler(platformView);
    }
}
  1. 在MauiProgram.cs中注册这个Handler:
builder.ConfigureMauiHandlers(handlers =>
{
#if ANDROID
    handlers.AddHandler<Editor, CustomEditorHandler>();
#endif
});

这样所有Editor在Android上都会带有完成按钮,点击触发Completed事件,回车键正常换行。

内容的提问来源于stack exchange,提问作者gfmoore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:33:28