MAUI iOS重写SendEvent后如何访问已注册服务?无法注入
在MAUI iOS中实现SendEvent并访问注册服务的方案
方法一:通过MAUI服务容器直接获取
在自定义的Sample类的SendEvent方法中,可借助MAUI应用上下文的服务容器获取已注册的服务。MAUI的服务容器可通过MauiContext访问,代码示例如下:
public override void SendEvent(UIEvent uievent) { if (uievent.Type == UIEventType.Touches) { if (uievent.AllTouches.Cast<UITouch>().Any(t => t.Phase == UITouchPhase.Began)) { // 获取MAUI服务容器 var mauiContext = Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext; if (mauiContext != null) { // 替换为你实际需要的服务接口 var myService = mauiContext.Services.GetService<IMyService>(); myService?.DoSomething(); // 调用服务方法 } } } base.SendEvent(uievent); }
如果担心重复获取MauiContext的开销,可在MAUI应用启动后将服务容器缓存为静态变量:
- 在
App.xaml.cs中添加静态属性:
public static IServiceProvider? AppServices { get; private set; } protected override void OnStart() { AppServices = Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext?.Services; }
- 随后在
Sample类中直接调用:
var myService = App.AppServices?.GetService<IMyService>();
方法二:不重写SendEvent,使用全局手势监听
若不想自定义UIApplication子类,可通过给应用主窗口添加全局手势识别器实现相同的触摸监听逻辑,同时也能便捷访问服务:
在iOS项目的AppDelegate类中,修改FinishedLaunching方法:
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { base.FinishedLaunching(app, options); var mainWindow = UIApplication.SharedApplication.KeyWindow; if (mainWindow != null) { var globalTapGesture = new UITapGestureRecognizer(() => { // 获取服务并处理逻辑 var mauiContext = Microsoft.Maui.Controls.Application.Current?.Handler?.MauiContext; var myService = mauiContext?.Services.GetService<IMyService>(); myService?.DoSomething(); }); globalTapGesture.CancelsTouchesInView = false; // 避免干扰其他控件的触摸事件 mainWindow.AddGestureRecognizer(globalTapGesture); } return true; }
这种方式无需重写SendEvent,更贴合MAUI的跨平台设计思路,同时能轻松访问已注册的服务。
内容的提问来源于stack exchange,提问作者developer9969
相关产品推荐
相关产品推荐

