publicclassPageService : IPageService { ///<summary> /// Service which provides the instances of pages. ///</summary> privatereadonly IServiceProvider _serviceProvider;
///<summary> /// Initializes a new instance of the <see cref="PageService"/> class and attaches the <see cref="IServiceProvider"/>. ///</summary> publicPageService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; }
///<inheritdoc /> public T? GetPage<T>() where T : class { if (!typeof(FrameworkElement).IsAssignableFrom(typeof(T))) { thrownew InvalidOperationException("The page should be a WPF control."); }
///<inheritdoc /> public FrameworkElement? GetPage(Type pageType) { if (!typeof(FrameworkElement).IsAssignableFrom(pageType)) { thrownew InvalidOperationException("The page should be a WPF control."); }
return _serviceProvider.GetService(pageType) as FrameworkElement; } }
现在已经将所有窗体、页面、ViewModels与相关服务都注册到容器中了。
ViewModel
在MainWindowViewModel中将页面存入一个属性中:
在非首页的ViewModel中实现INavigationAware接口:
View
MainWindow.cs如下所示:
publicpartialclassMainWindow : INavigationWindow { public ViewModels.MainWindowViewModel ViewModel { get; }
///<summary> /// Triggered when the application host is ready to start the service. ///</summary> ///<param name="cancellationToken">Indicates that the start process has been aborted.</param> publicasync Task StartAsync(CancellationToken cancellationToken) { await HandleActivationAsync(); }
///<summary> /// Triggered when the application host is performing a graceful shutdown. ///</summary> ///<param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param> publicasync Task StopAsync(CancellationToken cancellationToken) { await Task.CompletedTask; }
///<summary> /// Creates main window during activation. ///</summary> privateasync Task HandleActivationAsync() { await Task.CompletedTask;
if (!System.Windows.Application.Current.Windows.OfType<MainWindow>().Any()) { _navigationWindow = ( _serviceProvider.GetService(typeof(INavigationWindow)) as INavigationWindow )!; _navigationWindow!.ShowWindow();