Navigation in the WPF Application Between View Models

Navigation in the WPF Application Between View Models

In my previous post I showed adding a INavigateService to facilitate navigation between view models. This included an implementation of the service for Universal applications. For WPF the implementation looks very similar:

public class WPFNavigationService : CoreNavigateService<Page>
{
    protected override void NavigateToView(Type viewType)
    {
        (App.Current.MainWindow.Content as Frame).Navigate(new Uri(“/Pages/” + viewType.Name + “.xaml”, UriKind.RelativeOrAbsolute));
    }
}

Note that this assumes that pages are in the Pages folder of the project.

The other change that is required is that the WPF application needs to have a Frame which can be used to navigate between pages. So, the MainWindow now looks like

<Window x_Class=”RealEstateInspector.Desktop.MainWindow”
        http://schemas.microsoft.com/winfx/2006/xaml/presentation"”>http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        http://schemas.microsoft.com/winfx/2006/xaml"”>http://schemas.microsoft.com/winfx/2006/xaml”
        Title=”MainWindow” Height=”350″ Width=”525″
        >
    <Frame Source=”/Pages/MainPage.xaml” />
</Window>

All the content that was in the MainWindow is now in MainPage. And the type registration at application startup is getting more complex:

public void ApplicationStartup()
{
    CoreApplication.Startup(builder =>
    {

        builder.RegisterType<SignalRFactory>().As<ISignalR>();
#if NETFX_CORE
        builder.RegisterType<UniversalUIContext>().As<IUIContext>();
        builder.RegisterType<WindowsPlatformNavigationService>().SingleInstance().As<INavigateService>();

#elif DESKTOP
        builder.RegisterType<WPFNavigationService>().SingleInstance().As<INavigateService>();
#endif
    });

#if NETFX_CORE
    var navService = ServiceLocator.Current.GetInstance<INavigateService>() as WindowsPlatformNavigationService;
#elif DESKTOP
    var navService = ServiceLocator.Current.GetInstance<INavigateService>() as WPFNavigationService;
#endif
#if NETFX_CORE || DESKTOP
    navService.Register<MainViewModel, MainPage>();
    navService.Register<SecondViewModel, SecondPage>();
#endif
}

This creates a navigation bar which allows the user to navigate back between pages:

image

Leave a Reply

Your email address will not be published. Required fields are marked *