How to handle the back button on WP 8.1 using MVVM light?

admin

Administrator
Staff member
I'm searching for the appropiate way to handle the back button pressed event on Windows Phone 8.1 WinRT using the
Code:
NavigationService
available on MVVM light 5.

So far I think the best place to do it is inside the
Code:
ViewModelLocator
by registering the
Code:
GoBack
method of the
Code:
NavigationService
while creating it following the approach outlined in <a href="https://marcominerva.wordpress.com/2014/10/10/navigationservice-in-mvvm-light-v5/" rel="nofollow">NavigationService in MVVM Light V5</a>

This is an effective approach. However, I can't handle validation before navigating back so I was wondering if there is a more suitable way to handle this event.

Code:
public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() =&gt; SimpleIoc.Default);
        // Register NavigationService
        SimpleIoc.Default.Register(CreateNavigationService);
        // Register ViewModels here
    }

    private INavigationService CreateNavigationService()
    {
        var navigationService = new NavigationService();
        // Register pages here
        navigationService.Configure("Details", typeof(DetailsPage));
        // Handle back button
        HardwareButtons.BackPressed += (sender, args) =&gt; {
            navigationService.GoBack();
            args.Handled = true;
        }; 
        return navigationService;
    }
}