Xamarin.Forms从4.8升级到5后UWP项目在应用设计器页崩溃如何解决
Xamarin.Forms 5.x UWP CarouselView 空委托异常解决方案
问题触发场景
将Xamarin.Forms从4.8版本升级到5.x版本后,UWP项目在设计器页面加载时触发未处理异常崩溃。
异常信息
异常提示:
Delegate to an instance method cannot have null 'this'.
完整调用栈:System.ArgumentException: Delegate to an instance method cannot have null 'this'. at System.MulticastDelegate.ThrowNullThisInDelegateToInstance() at Xamarin.Forms.Platform.UWP.CarouselViewRenderer.InitialSetup(Object sender, SizeChangedEventArgs e)
修复方案
- 方案1:升级Xamarin.Forms Nuget包到5.0.0.2515及以上正式版本,该问题已被官方修复,升级后清理解决方案、删除bin/obj缓存重新编译即可生效。
- 方案2:临时回退到4.8版本旧渲染器,在UWP项目的
App.xaml.cs文件中,Xamarin.Forms.Forms.Init()方法执行前添加如下配置:
Xamarin.Forms.Forms.SetFlags("CarouselView_LegacyRenderer");
- 方案3:自定义渲染器规避空引用风险,在UWP项目中新增自定义CarouselView渲染器,手动控制事件绑定生命周期:
using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; // 替换为你项目的对应命名空间 using YourProjectNamespace; using YourProjectNamespace.UWP.Renderers; [assembly: ExportRenderer(typeof(CarouselView), typeof(CustomCarouselViewRenderer))] namespace YourProjectNamespace.UWP.Renderers { public class CustomCarouselViewRenderer : CarouselViewRenderer { protected override void OnElementChanged(ElementChangedEventArgs<CarouselView> e) { if (e.OldElement != null) { SizeChanged -= InitialSetup; } base.OnElementChanged(e); // 仅当控件和绑定元素都非空时绑定事件 if (e.NewElement != null && Control != null) { SizeChanged += InitialSetup; } } } }
修改完成后重新编译项目即可生效。
内容的提问来源于stack exchange,提问作者Charmy
相关产品推荐
相关产品推荐

