Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

So far I think the best place to do it is inside the ViewModelLocator by registering the GoBack method of the NavigationService while creating it following the approach outlined in NavigationService in MVVM Light V5

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.

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => 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) => {
            navigationService.GoBack();
            args.Handled = true;
        }; 
        return navigationService;
    }
}
like image 351
Camilo Martinez Avatar asked Jan 17 '26 22:01

Camilo Martinez


1 Answers

If you take a look at how Marco is enabling OnNavigatedTo and OnNavigatedFrom calls to propagate to ViewModel in the blog post

Calling ViewModel methods in response to Page navigation events using MVVM Light in WinRT

you'll notice he uses INavigable interface and Activate and Deactivate methods. You could extend that INavigable interface with AllowGoingBack method, like this:

public interface INavigable
{
    void Activate(object parameter);
    void Deactivate(object parameter);
    bool AllowGoingBack();
}

Each page-related ViewModel can then have its own implementation of AllowGoingBack method depending on the context. Then, in the code behind of the View (which is OK, because View can know about the ViewModel) you can override OnNavigatingFrom and check if going back should be allowed:

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    var navigableViewModel = this.DataContext as INavigable;

    if (navigableViewModel != null)
    {
        if (e.NavigationMode == NavigationMode.Back && !navigableViewModel.AllowGoBack())
        {
            e.Cancel = true;
        }
    }
}

Your ViewModel would then implement INavigable, so you would define the validation code inside AllowGoingBack(), and return true if going back is OK, and false if it's not.

like image 60
Igor Ralic Avatar answered Jan 20 '26 11:01

Igor Ralic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!