您可以使用Windows Template Studio创建测试应用程序并检查导航页面项目类型,然后检查棱镜设计模式。你会_navigationService
在ShellViewModel
课堂上找到。
适用于 Windows Template Studio Prism
_navigationService.Navigate(pageKey, null);
ShellViewModel.cs
public class ShellViewModel : ViewModelBase
{
private static INavigationService _navigationService;
private WinUI.NavigationView _navigationView;
private bool _isBackEnabled;
private WinUI.NavigationViewItem _selected;
public ICommand ItemInvokedCommand { get; }
public bool IsBackEnabled
{
get { return _isBackEnabled; }
set { SetProperty(ref _isBackEnabled, value); }
}
public WinUI.NavigationViewItem Selected
{
get { return _selected; }
set { SetProperty(ref _selected, value); }
}
public ShellViewModel(INavigationService navigationServiceInstance)
{
_navigationService = navigationServiceInstance;
ItemInvokedCommand = new DelegateCommand<WinUI.NavigationViewItemInvokedEventArgs>(OnItemInvoked);
}
public void Initialize(Frame frame, WinUI.NavigationView navigationView)
{
_navigationView = navigationView;
frame.NavigationFailed += (sender, e) =>
{
throw e.Exception;
};
frame.Navigated += Frame_Navigated;
_navigationView.BackRequested += OnBackRequested;
}
private void OnItemInvoked(WinUI.NavigationViewItemInvokedEventArgs args)
{
var item = _navigationView.MenuItems
.OfType<WinUI.NavigationViewItem>()
.First(menuItem => (string)menuItem.Content == (string)args.InvokedItem);
var pageKey = item.GetValue(NavHelper.NavigateToProperty) as string;
_navigationService.Navigate(pageKey, null);
}
private void Frame_Navigated(object sender, NavigationEventArgs e)
{
IsBackEnabled = _navigationService.CanGoBack();
Selected = _navigationView.MenuItems
.OfType<WinUI.NavigationViewItem>()
.FirstOrDefault(menuItem => IsMenuItemForPageType(menuItem, e.SourcePageType));
}
private void OnBackRequested(WinUI.NavigationView sender, WinUI.NavigationViewBackRequestedEventArgs args)
{
_navigationService.GoBack();
}
private bool IsMenuItemForPageType(WinUI.NavigationViewItem menuItem, Type sourcePageType)
{
var sourcePageKey = sourcePageType.Name;
sourcePageKey = sourcePageKey.Substring(0, sourcePageKey.Length - 4);
var pageKey = menuItem.GetValue(NavHelper.NavigateToProperty) as string;
return pageKey == sourcePageKey;
}
}
_navigationService
来自 ShellViewModel 构造方法。这个实例是在App
类中创建的。
protected override UIElement CreateShell(Frame rootFrame)
{
var shell = Container.Resolve<ShellPage>();
shell.SetRootFrame(rootFrame);
return shell;
}