How can I use MVVM's Light NavigationService with subframes, like in NavigationView control?

573 views Asked by At

The NavigationService system that comes with MVVM Light seems to assume that I want to make the whole window navigate to another page, however, I would like to have a lateral bar from which I can select to which page to go, something like a hamburger menu in cellphone apps. That is, I only want to navigate using this frame that is inside a NavigationView.Content.

I could get it going by binding the content frame to the MainPageViewModel and navigate using it, but I would rather use the NavigationService provided by MVVM Light to learn it better.

Thanks for the help!

1

There are 1 answers

0
Xie Steven On

I could get it going by binding the content frame to the MainPageViewModel and navigate using it, but I would rather use the NavigationService provided by MVVM Light to learn it better.

You're on the right direction. Even if you use the NavigationService class provided by MVVMLight, you still need to provide your content frame instance for its CurrentFrame property. You could check its source code on GitHub.

For example,

var nav = ServiceLocator.Current.GetInstance<NavigationService>();
nav.CurrentFrame = YourframeControl;

Here, I wanted to provide an easy way to you. You could try to use the WindowsTemplateStudio to create your UWP project. You could choose 'Navigation Pane' project type and 'Mvvm Light' design pattern. Then, you would find that the 'WindowsTemplateStudio' has helped you do all relevant things. On the 'ShellPage.xaml', it has a NavigationView control for navigation. It also has implemented a NavigationServiceEx class for you.

In the ViewModelLocator.cs:

public NavigationServiceEx NavigationService => SimpleIoc.Default.GetInstance<NavigationServiceEx>();

In the 'ShellPage.xaml.cs':

ViewModel.Initialize(shellFrame, navigationView, KeyboardAccelerators);

This will do the same thing as my code above. Then, when you use the NavigationService to navigate to other page, it will use the 'shellFrame' control to navigate.