Search code examples
xamluwpmvvmcrossmaster-detail

Enable back button in NavigationView of UWP app with MvvmCross


My UWP app uses the MvvmCross framework and has a NavigationView with a main and a detail page, as you can see in the illustration and folder structure. Both of these pages are annotated with [MvxSplitViewPresentation(SplitPanePosition.Content)] to display them on the content side. Now I want to add a working back button on the detail view, but I do not know how to enable the button and navigate back.

Info: My detail page is opened by calling _navigationService.Navigate<DetailViewModel>(); in the MainViewModel.

├── ViewModels
│   ├── NavigatonRootsViewModel.cs
│   ├── MainViewModel.cs
│   └── DetailViewModel.cs
├── Views
│   ├── NavigationRoot.xaml
│   ├── NavigationRoot.xaml.cs
│   ├── Main.xaml
│   ├── Main.xaml.cs
│   ├── Detail.xaml
│   └── Detail.xaml.cs

Solution

  • NavigationView has a built-in back button, you could set IsBackEnabled as True to display it and subscribe the BackRequested event to control the navigate back operation in it.

    .xaml:

    <NavigationView IsBackEnabled="True" BackRequested="NavigationView_BackRequested">
        ......
    <NavigationView>
    

    .cs:

    Update:

    By checking the code, the page isn't loaded in the FrameContent, the NavigationView has it build-in Frame, so you can use the VisualTreeHelper to get the Frame by referring to this thread. Then use GoBack() method to navigate back.

    private void NavigationView_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
    { 
        //use the MyFindListBoxChildOfType method from the link.
        var MyFrame = MyFindListBoxChildOfType<Frame>(NaviView); 
        if (MyFrame.CanGoBack) 
        {
            MyFrame.GoBack();
        }
    }
    

    Demo application: DemoMvvmCrossNavigation