Search code examples
c#mvvmuwpnavigationviewnavigationservice

UWP NavigationView switch to another page via MVVM


Switching for the first time ever from WPF to UWP I found out that there are great controls like SplitView and NavgiationView do exist in the world of UWP.

For renewing my current home-project I have choosen the NavigationView control as my main UI control for offering the various pieces of information. Using the code-behind the page navigation (as shown here) is very easy, but for my use-case I want to work with MVVM (as a learning procedure without using FWs like MVVMLIght or similar).

Currently, my NavigationView looks like this; but I have not a proper idea how to change within the frame through pages (from my understanding I have to use the NavigationService but haven't found a easy to understand example of this):

<NavigationView x:Name="nvTopLevelNav" Grid.Column="0" Grid.Row="1" Grid.RowSpan="3" IsPaneOpen="False"  IsPaneToggleButtonVisible="False" CompactModeThresholdWidth="0" IsBackButtonVisible="Collapsed" Background="Black" Foreground="Black"
        Loaded="nvTopLevelNav_Loaded"
        Margin="0,12,0,0"
        SelectionChanged="nvTopLevelNav_SelectionChanged"
        ItemInvoked="nvTopLevelNav_ItemInvoked"
        IsTabStop="False"
                IsSettingsVisible="False"
                AlwaysShowHeader="False"
        Header="asdasdaasdasdasd">
    <NavigationView.MenuItems>
        <NavigationViewItem Icon="Home" Content="Home" Tag="Home_Page" />
        <NavigationViewItem Icon="Globe" Content="Weather" Tag="Weather_Page" />
        <NavigationViewItem Content="My Agenda" Tag="Agenda_Page">
    <!-- some custom PathIcon -->
        </NavigationViewItem>
        <NavigationViewItem Icon="Contact" Content="My News" Tag="News_Page" />
    </NavigationView.MenuItems>
    <Frame x:Name="contentFrame"></Frame>
</NavigationView>

Solution

  • UWP NavigationView switch to another page via MVVM

    For your requirement, you could use Windows Template Studio to create UWP project that contain MVVM pattern and NavigationService.

    private void OnItemInvoked(NavigationViewItemInvokedEventArgs args)
    {
        if (args.IsSettingsInvoked)
        {
            NavigationService.Navigate(typeof(SettingsViewModel).FullName);
            return;
        }
    
        var item = _navigationView.MenuItems
                        .OfType<NavigationViewItem>()
                        .First(menuItem => (string)menuItem.Content == (string)args.InvokedItem);
        var pageKey = item.GetValue(NavHelper.NavigateToProperty) as string;
        NavigationService.Navigate(pageKey);
    }
    

    enter image description here