Cancel page navigation in MVVM Light and WinRT

Cancel page navigation in MVVM Light and WinRT

There are often situations in which you may want to cancel navigation. Imagine a form being filled in, and all of a sudden user accidentaly presses back button and ... whooops ... all entered data is gone. In that particular situation you might want to ask the user if he wanted to do that and if he wanted to preserve the data already entered. This article shows how to do it "MVVM-way" using MVVM Light.

When it comes to properly handling navigating to and from a page using MVVM Light, I really like the approach suggested by Marco Minerva in his blog post: "Calling ViewModel methods in response to Page navigation events using MVVM Light in WinRT". Having the INavigable interface makes it clean and I think it's OK that the page calls the methods in the code-behind as it knows about the DataContext anyway.

So, to be able to cancel the navigation, we can extend this approach by extending the interface first with another method, CanNavigateAway.

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

BindablePage can be extended to handle OnNavigatingFrom

public class BindablePage : Page  
{
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        var navigableViewModel = this.DataContext as INavigable;

        if (navigableViewModel != null)
        {
            if (!navigableViewModel.CanNavigateAway())
            {
                e.Cancel = true;
            }
        }
    }

    // other overrides
}

So every ViewModel which is a DataContext for the BindablePage can implement its own logic for CanNavigateAway method, depending on the context.

public class MainViewModel : ViewModelBase, INavigable  
{
    public bool CanNavigateAway()
    {
        // if there's some unsaved state, return false, else return true
    }
}

I hope this helps you in keeping things clean and reusable!

Igor Ralic

igor ralic

View Comments
Microsoft Certified Solutions Developer: Windows Store Apps in C#