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

MAUI MVVM(Prism)中Snackbar后续页面不显示的解决方法

解决Prism MAUI中Snackbar在后续页面不显示的问题

核心原因

你猜的没错:Snackbar默认锚定到Application.Current.MainPage,导航到后续页面后,首页仍在导航栈底层,Snackbar会显示在首页上并被当前页面完全遮挡,所以看不到。解决关键是把Snackbar的锚点设置为当前活跃的页面。

具体实现方案

方案1:利用Prism导航服务获取当前页面(推荐,通用性强)

Prism的INavigationService自带CurrentPage属性,可直接获取导航栈最顶部的活跃页面,无需手动传递页面实例。

步骤1:修改NotificationService,支持接收锚点页面

public class NotificationService
{
    // 重载ShowSuccess方法,新增锚点参数
    public async Task ShowSuccess(string message, Page anchorPage = null)
    {
        // 未传锚点时, fallback到MainPage(兼容首页场景)
        var anchor = anchorPage ?? Application.Current.MainPage;
        
        var snackbar = Snackbar.Make(
            message: message,
            action: null,
            actionButtonText: string.Empty,
            duration: TimeSpan.FromSeconds(3),
            anchor: anchor // 指定锚点为当前页面
        );

        await snackbar.ShowAsync();
    }
}

步骤2:在ViewModel中注入INavigationService,调用时传递当前页面

public class YourSubPageViewModel : BindableBase
{
    private readonly INavigationService _navigationService;
    private readonly NotificationService _notificationService;

    public IAsyncCommand ShowSuccessCommand { get; }

    public YourSubPageViewModel(INavigationService navigationService, NotificationService notificationService)
    {
        _navigationService = navigationService;
        _notificationService = notificationService;
        ShowSuccessCommand = new AsyncCommand(ExecuteShowSuccess);
    }

    private async Task ExecuteShowSuccess()
    {
        // 获取当前活跃页面
        var currentPage = _navigationService.CurrentPage;
        await _notificationService.ShowSuccess("操作完成", currentPage);
    }
}

方案2:页面后台手动传递当前页面实例(适合特殊场景)

如果某些页面无法通过INavigationService获取正确的当前页,可在页面后台把自身实例传递给ViewModel:

步骤1:ViewModel中添加CurrentPage属性

public class YourSubPageViewModel : BindableBase
{
    private readonly NotificationService _notificationService;
    public Page CurrentPage { get; set; }

    public IAsyncCommand ShowSuccessCommand { get; }

    public YourSubPageViewModel(NotificationService notificationService)
    {
        _notificationService = notificationService;
        ShowSuccessCommand = new AsyncCommand(ExecuteShowSuccess);
    }

    private async Task ExecuteShowSuccess()
    {
        await _notificationService.ShowSuccess("操作完成", CurrentPage);
    }
}

步骤2:页面后台传递自身实例

public partial class YourSubPage : ContentPage
{
    public YourSubPage(YourSubPageViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
        // 将当前页面实例传给ViewModel
        viewModel.CurrentPage = this;
    }
}

验证效果

导航到后续页面后调用ShowSuccess,Snackbar会锚定在当前页面底部显示,不会被遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:52:46