C# WinUI Template Studio如何在处理过程中阻止页面导航
临时禁用WinUI Template Studio应用的导航功能
以下是几种适配Template Studio架构的实用实现方式:
方法一:通过ShellViewModel控制导航触发
- 在
ShellViewModel中添加标记导航状态的属性:
using CommunityToolkit.Mvvm.ComponentModel; namespace YourAppNamespace.ViewModels; public partial class ShellViewModel : ObservableObject { // 保留原有代码... [ObservableProperty] private bool _isNavigationDisabled; }
- 在
ShellPage.xaml.cs中拦截导航项点击事件,判断状态后取消导航:
private void NavigationView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args) { var viewModel = DataContext as ShellViewModel; if (viewModel?.IsNavigationDisabled == true) { args.Handled = true; // 可选:弹出提示告知用户当前无法导航 _ = new ContentDialog { Title = "处理中", Content = "当前正在执行任务,请稍候", CloseButtonText = "确定" }.ShowAsync(); return; } // 保留原有的导航逻辑 var item = args.InvokedItemContainer as NavigationViewItem; if (item?.Tag is not null) { _viewModel.Navigate(item.Tag.ToString()); } }
- 同步禁用返回按钮逻辑,修改
ShellViewModel中的返回命令:
using CommunityToolkit.Mvvm.Input; [RelayCommand(CanExecute = nameof(CanGoBack))] private void GoBack() { _navigationService.GoBack(); } private bool CanGoBack() { return !IsNavigationDisabled && _navigationService.CanGoBack; }
方法二:直接禁用NavigationView交互(简单粗暴)
如果不需要保留NavigationView的展开/收起等其他交互,可直接控制其启用状态:
// 在处理开始时禁用 ShellPage.Current.NavigationView.IsEnabled = false; // 处理完成后恢复 ShellPage.Current.NavigationView.IsEnabled = true;
注意:需在
ShellPage中添加静态属性并初始化:public static ShellPage Current { get; private set; } public ShellPage() { InitializeComponent(); Current = this; // 其他初始化代码... }
方法三:拦截导航服务的请求
从导航服务层面拦截,修改ShellViewModel的导航命令:
[RelayCommand] private void Navigate(string pageKey) { if (IsNavigationDisabled) return; _navigationService.NavigateTo(pageKey); }
状态切换方式
在处理任务的页面ViewModel中,获取ShellViewModel实例并切换状态:
var shellViewModel = App.GetService<ShellViewModel>(); shellViewModel.IsNavigationDisabled = true; // 执行你的处理逻辑... // 处理完成后恢复导航 shellViewModel.IsNavigationDisabled = false;
内容的提问来源于stack exchange,提问作者PIGRECO
相关产品推荐
相关产品推荐

