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

.NET 8中如何在非单项目的iOS头项目注册自定义Handler?

.NET 8多项目架构下iOS自定义Handler注册方案

在.NET 8中,原有的Microsoft.Maui.Handlers.Handlers.AddHandler静态调用方式已被弃用,针对多项目架构(共享项目无法引用iOS平台代码)的场景,推荐以下两种实现方式:

方式一:通过iOS项目的Program.cs配置(官方推荐)

  1. 在iOS项目中创建静态扩展类,封装Handler注册逻辑:
using Microsoft.Maui.Hosting;
using [你的共享项目命名空间];

namespace [你的iOS项目命名空间];

public static class MauiHandlerExtensions
{
    public static MauiAppBuilder ConfigureiOSCustomHandlers(this MauiAppBuilder builder)
    {
        builder.ConfigureMauiHandlers(handlers =>
        {
            handlers.AddHandler<MyCustomControl, MyCustomControlHandler>();
        });
        return builder;
    }
}
  1. 修改iOS项目的Program.cs,在构建MauiApp时调用该扩展方法:
using Microsoft.Maui.Hosting;
using [你的共享项目命名空间];
using [你的iOS项目命名空间];

namespace [你的iOS项目命名空间];

public class Program
{
    static void Main(string[] args)
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            // 添加iOS平台自定义Handler配置
            .ConfigureiOSCustomHandlers();

        var app = builder.Build();
        app.Run(args);
    }
}

方式二:在AppDelegate中通过服务注册

如果偏好在AppDelegate中处理,可通过依赖注入获取IMauiHandlerRegistry完成注册:

using Microsoft.Maui;
using Microsoft.Maui.Hosting;
using [你的共享项目命名空间];

namespace [你的iOS项目命名空间];

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        var mauiApp = CreateMauiApp();
        var handlerRegistry = mauiApp.Services.GetRequiredService<IMauiHandlerRegistry>();
        handlerRegistry.RegisterHandler<MyCustomControl, MyCustomControlHandler>();

        return base.FinishedLaunching(application, launchOptions);
    }
}

注意事项

  • 确保MyCustomControl定义在共享项目中,MyCustomControlHandler定义在iOS项目中,保证类型可跨项目识别。
  • 优先使用方式一,符合.NET MAUI的模块化配置设计,代码更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:27:50