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

更换MAUI应用MainPage致OnBackPressedDispatcher回调失效问题

.NET8 MAUI Android 13 替换MainPage后返回按键回调失效问题

我已将MAUI应用升级至.NET8并适配Android 13,正尝试移除已弃用的base.OnBackPressed();,但遇到问题。

旧逻辑

// MainActivity.cs
public override void OnBackPressed()
{
    if (someCondition() == true)
    {
        HandleBackPressMyself();
    }
    else
    {
        base.OnBackPressed();
    }
}

页面启动方式

// App.xaml.cs
public App()
{
    InitializeComponent();
    Start();
}

private async void Start()
{
    var page = serviceProvider.GetRequiredService<MyFirstPage>();
    Application.Current?.Dispatcher.Dispatch(async () =>
    {
        ((App)Application.Current).MainPage = page;
        await Task.Delay(1);
    });
}

该逻辑一直正常运行。现在我尝试使用OnBackPressedDispatcher:

新实现代码

MainActivity.cs

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    OnBackPressedDispatcher.AddCallback(this, new BackPressedCallback(this));
}

BackPressedCallback.cs

public class BackPressedCallback : OnBackPressedCallback
{
    private readonly Activity activity;

    public BackPressedCallback(Activity activity) : base(true)
    {
        this.activity = activity;
    }

    public override void HandleOnBackPressed()
    {
        if (someCondition() == true)
        {
            HandleBackPressMyself();
        }
        else
        {
            var mainPage = ((App)Microsoft.Maui.Controls.Application.Current)?.MainPage;
            mainPage.SendBackButtonPressed();
        }
    }
}

使用await navigationPage.PushAsync(newPage);推送新页面时一切正常,但当通过((App)Application.Current).MainPage = loginPage;替换MainPage后,BackPressedCallback中的HandleOnBackPressed()停止触发,返回导航完全失效。

请问为何设置Application.Current.MainPage = someNewPage后返回处理程序会停止工作?


更新

我已上传问题演示项目至GitHub仓库。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:40:16