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

.NET MAUI在Android模拟器调用DisplayAlert时触发NullReferenceException

.NET MAUI 弹窗提示NullReferenceException 解决办法

问题原因

模拟器/调试器的页面初始化流程比真机慢,当Info_Appearing事件触发时,Application.Current.MainPage可能还未完成赋值,导致空引用异常;真机初始化速度更快,因此不会出现该问题。

解决方法

  • 检查MainPage是否为空后再调用
    增加空值判断,避免直接访问null对象:

    private async void Info_Appearing(object sender, EventArgs e)
    {
        if (Application.Current?.MainPage != null)
        {
            await Application.Current.MainPage.DisplayAlert("Title", "Text", "OK");
        }
    }
    
  • 改用当前页面的DisplayAlert
    直接使用触发事件的当前页面调用弹窗,无需依赖MainPage:

    private async void Info_Appearing(object sender, EventArgs e)
    {
        if (sender is Page currentPage)
        {
            await currentPage.DisplayAlert("Title", "Text", "OK");
        }
    }
    
  • 延迟执行适配模拟器
    给MainPage初始化留足时间,适合模拟器启动较慢的场景:

    private async void Info_Appearing(object sender, EventArgs e)
    {
        await Task.Delay(100); // 可根据实际情况调整延迟时长
        if (Application.Current?.MainPage != null)
        {
            await Application.Current.MainPage.DisplayAlert("Title", "Text", "OK");
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:55:47