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

.NET MAUI 按官方文档实现Custom Handlers报错CS0021如何解决?

报错原因

该错误是因为.NET MAUI 正式版的IPropertyMapper接口已不支持直接通过索引器[]赋值的操作,你参考的官方文档示例对应较早的预览版API,正式版需要使用ModifyProperty方法修改属性映射逻辑。

解决步骤

  1. 你定义的MyEntry子类代码无需修改,保持原有逻辑即可。
  2. 不要在App构造函数中配置Handler映射,推荐统一在MauiProgram.cs的CreateMauiApp方法中配置,正确代码如下:
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Hosting;
using Microsoft.Maui.Graphics;
using MyMauiApp; // 引入MyEntry所在的命名空间

namespace MauiApp1
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureMauiHandlers(handlers =>
                {
                    // 修改Entry的Background属性映射逻辑
                    Microsoft.Maui.Handlers.EntryHandler.EntryMapper
                        .ModifyProperty(nameof(IView.Background), (handler, view) =>
                        {
                            if (view is MyEntry)
                            {
#if __ANDROID__
                                handler.NativeView.SetBackgroundColor(Colors.Red.ToNative());
#elif __IOS__
                                handler.NativeView.BackgroundColor = Colors.Red.ToNative();
                                handler.NativeView.BorderStyle = UIKit.UITextBorderStyle.Line;
#elif WINDOWS
                                handler.NativeView.Background = Colors.Red.ToNative();
#endif
                            }
                        });
                });

            return builder.Build();
        }
    }
}
  1. 删除App.xaml.cs构造函数中原有的Handler配置代码,重新编译即可解决报错。

最佳实践补充

如果你不希望修改全局EntryHandler的逻辑影响其他普通Entry控件,可以为MyEntry单独注册专属Handler,隔离自定义逻辑:

// 在ConfigureMauiHandlers中添加以下代码
handlers.AddHandler(typeof(MyEntry), typeof(MyEntryHandler));

// 单独定义MyEntry的专属Handler
public class MyEntryHandler : Microsoft.Maui.Handlers.EntryHandler
{
    public static void MapBackground(MyEntryHandler handler, MyEntry view)
    {
#if __ANDROID__
        handler.NativeView.SetBackgroundColor(Colors.Red.ToNative());
#elif __IOS__
        handler.NativeView.BackgroundColor = Colors.Red.ToNative();
        handler.NativeView.BorderStyle = UIKit.UITextBorderStyle.Line;
#elif WINDOWS
        handler.NativeView.Background = Colors.Red.ToNative();
#endif
    }

    public static IPropertyMapper<MyEntry, MyEntryHandler> MyEntryMapper =
        new PropertyMapper<MyEntry, MyEntryHandler>(EntryMapper)
        {
            [nameof(IView.Background)] = MapBackground
        };

    public MyEntryHandler() : base(MyEntryMapper)
    {
        
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:27:08