One of the things that’s often given me pause for thought is the approach we take to navigation within applications. For the purpose of this post I’m going limit the scope to just XAML based applications (XF/Maui, UWP/WinUI/Uno, WPF). In all of these application platforms there is a built in capability to navigate between pages. However, once we introduce view models, we want to be able to drive navigation from our view models. In this post I’m going to go through a bit of a thought journey to look at some of the existing strategies for view model navigation, discuss the pros and cons, and then look at whether we can build an alternative.
Rather than try to cover all the XAML platforms at every point along the way, I’m going to use a newly created @unoplatform application throughout this post. Towards the end we’ll look at whether we can adapt what we’ve created to the other XAML platforms – if we’ve done the job well, it should be a relatively easy thing to do.
Basic Page Navigation
As part of creating our project, MvvmNavigation, we’re given a MainPage, which is clearly the starting point of our application. To begin with, let’s:
- Create another page, SecondPage
- Add a Button to MainPage and an event handler that will simply navigate to SecondPage
- Add a Button to SecondPage and an event handler to navigate back to MainPage
- Add a TextBlock to both pages to give the pages a title
The XAML for MainPage
<Page x:Class="MvvmNavigation.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MvvmNavigation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="Main Page"
Margin="100"
FontSize="50"
HorizontalAlignment="Center" />
<Button Content="Go to Second Page"
Click="GoToSecondPageClick"
VerticalAlignment="Bottom"
HorizontalAlignment="Center"
Margin="100" />
</Grid>
</Page>
The GoToSecondPageClick event handler in the codebehind of MainPage
private void GoToSecondPageClick(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(SecondPage));
}
The XAML for SecondPage
<Page x:Class="MvvmNavigation.SecondPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MvvmNavigation.Shared"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="Second Page"
Margin="100"
FontSize="50"
HorizontalAlignment="Center" />
<Button Content="Go back to Main Page"
Click="GoBackClick"
VerticalAlignment="Bottom"
HorizontalAlignment="Center"
Margin="100" />
</Grid>
</Page>
The GoBackClick event handler in the codebehind of SecondPage
private void GoBackClick(object sender, RoutedEventArgs e)
{
Frame.GoBack();
}
And final a screenshot of each page that we’re navigating between.
What we can see from this example is that in a UWP/Uno application, navigating between pages is done by calling navigation methods on the Frame. As an aside, a UWP application can not only support multiple Windows, it can also support multiple frames. This can be very handy if you’re building complex desktop applications where you want to be able to control multiple page stacks. For the moment we’ll keep things simple and just consider a single window, single frame application.
ViewModel Navigation
Let’s augment our example by adding in some view models. To ensure we don’t pollute our view models with UI/framework specific code, we’ll add our view models to a separate .NET Standard class library, MvvmNavigation.Core. In this case I’ll create a view model for each page we currently have.
public class MainViewModel
{
public string Title { get; } = "Main Page - VM";
}
public class SecondViewModel
{
public string Title { get; } = "Second Page - VM";
}
One thing you’ll notice about a lot of mvvm frameworks is that they all seem to have their own base class. Where possible, I’m going to try to avoid this, in order to keep our view models as simple as possible. If you want to have bindings update the viewmodel will need to implement INotifyPropertyChanged, so having a base class with that implementation is something you’ll want to add. For the moment we’ll keep the view models as simple as possible.
Now let’s connect our view models to our pages. We’ll keep this really simple by creating the view models inline in the page as part of setting the DataContext. We’ll also update the Text on the TextBlock to bind to the Title property on the view model.
<Page x:Class="MvvmNavigation.MainPage" ... >
<Page.DataContext>
<vms:MainViewModel />
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="{Binding Title}" ... />
...
</Page>
With the basic setup done, we can start to think about navigation. Firstly, let’s set the scene as to why the current navigation (i.e. controlled invoked in the code behind of the page) is a problem. In our MainViewModel, let’s say we have a method that does something, DoSomething.
public async Task<int> DoSomething()
{
var rnd = new Random().Next(1000);
await Task.Delay(rnd);
if (rnd % 2 == 0)
{
// Do one thing
}
else
{
// Do something else
}
return rnd;
}
After delaying for a random amount of time, it decides to do one of two things. Let’s assume that if the random number is even, the app should navigate to SecondPage. However, currently the view model doesn’t have a way to do this. We could augment the return value to return a flag to indicate that it should navigate. Alternatively, we could move the decision logic into the code behind. I don’t like either of these options and it would be much clearer if the view model had a way to invoke navigation itself.
This leads us to a quick discussion on how this is currently implemented by different frameworks. Typically the solution is to pass in a service, call it something like INavigationService, into the constructor for the view model. When the view model wants to navigate it calls a method, such as Navigate, on the service. Depending on which framework it is, the parameter might be a url or it could be the type of view model to navigate to (i.e. navigate to the page that is associated with the specified view model type).
My issue with this approach is two fold. Firstly, we’ve added a dependency to the view model that doesn’t really assist the view model with what it needs to do (controlling the state for the view; loading and updating data that’s data bound to the UI etc). Secondly, we’ve added in an implicit linkable between the current view model and the view model that’s being navigated to.
If I had to pick between navigating using a url versus the type of a view model, my preference is the type of a view model, purely because this can be enforced with type safety. However, my point is that in both cases there’s an implied link that’s only visible if you walk the code of the view model.
Event Based Navigation
Instead of using an injected navigation service, what if we simply expose an event on the view model for when we need navigation to take place. For example, our MainViewModel could look like
public class MainViewModel
{
public event EventHandler ViewModelDone;
public async Task<int> DoSomething()
{
var rnd = new Random().Next(1000);
await Task.Delay(rnd);
if (rnd % 2 == 0)
{
ViewModelDone?.Invoke(this, EventArgs.Empty);
}
...
}
}
Note that I didn’t call the event NavigateToSecondPage because this would again start to build in that implicit linkage between the view models/pages. The point is that the MainViewModel doesn’t, and shouldn’t, care about what’s going to happen next, it just knows that it’s time is up and it’s job is done.
The only thing now, is that we need something to listen to the event. For the moment this will be the MainPage:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
(DataContext as MainViewModel).ViewModelDone += MainViewModelDone;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
(DataContext as MainViewModel).ViewModelDone -= MainViewModelDone;
base.OnNavigatedFrom(e);
}
private void MainViewModelDone(object sender, EventArgs e)
{
Frame.Navigate(typeof(SecondPage));
}
private void GoToSecondPageClick(object sender, RoutedEventArgs e)
{
(DataContext as MainViewModel)?.DoSomething();
}
Whilst we’ve kept our MainViewModel clear of any dependency/relationship with SecondPage or SecondViewModel, what we’ve ended up with is a bunch of wiring and navigation logic in our MainPage.
Abstracting Navigation Logic
Let’s step away from the specifics of how events and navigation logic works and think about what we want to achieve. Essentially we need a way of defining a set of behaviours such that when an event is raised on a particular object, the application will navigate to a particular page. So, for each behaviour we want to define, we need a way to declare the event that is going to be listened for and the action that should take place when that event is triggered.
The complexity in abstracting the navigation logic comes when you attempt to declare these behaviours at an application level. At a page level you can simply attach and detach event handlers, similar to what we’ve just done with MainPage in the OnNavigatedTo and OnNavigatedFrom methods. At an application level, you don’t have the instances of the pages until the user has navigated to them. As such, we’ll need to hook into the navigation event on the Frame and wire/unwire the event handlers.
Here’s a summary of the pieces we need:
- Behaviour class – this will define the event to listen to and the action to execute
- NavigationRoutes class – this will hold the list of behaviours for the application
- OnNavigation method – this is the event handler for the Navigated event on the root frame of the application
Let me try to walk through these in a way that hopefully makes sense. We’ll start with the behaviour class.
public class Behaviour:IApplicationBehaviour
{
public Action<object> Init { get; set; }
public Action<object> Deinit { get; set; }
private Behaviour() { }
public static Behaviour Create<T, THandler>(Action<T, THandler> init, Action<T, THandler> deinit, THandler action)
{
return new Behaviour()
{
Init = obj => init((T)obj, action),
Deinit = obj => deinit((T)obj, action)
};
}
}
public interface IApplicationBehaviour
{
Action<object> Init { get; set; }
Action<object> Deinit { get; set; }
}
According to what I said earlier, the behaviour class needs to define an event and an action, yet the implementation doesn’t really look like it has either. It does, they’re just masked a little.
Firstly, the challenge with an event in C# is that you can’t easily just pass the event object around and attach/detach from it. We could have just switched it out for an Action or some other delegate but that would make the programming model for the view model just a bit weird. Alternatively we could have used some hocky reflection to get the job done but … well just, no… I don’t want to be doing reflection due to the inherit overhead and potential linker issues it might create.
Instead of passing an event object around, we instead pass in an Action for wiring and unwiring the event. For example the wiring action would look something like (vm, act) => vm.ViewModelDone += act
.
Next, we need the action that’s going to be invoked. Well this is easily identifiable in the Create method as the third parameter but then what do we do with it? Rather than hold a direct reference to the action, we simply combine it with the init and deinit Action delegates and assign them to the public Init and Deinit methods.
Initially this looks a bit strange as the signature on the Init and Deinit methods are Action<object>
instead of Action<T>
, and then we’re assigning a delegate that coerces the object into T – why not just make them Action<T>
? The answer to this comes if you look at the interface IApplicationBehaviour that defines Init and Deinit methods, both as Action<object>. As you’ll see shortly, we’re going to have a collection of these behaviours defined for a variety of different pages (i.e. T). Rather than attempt to keep these as strongly typed behaviours, we’re simply going to use an interface which doesn’t include the type argument.
You might be wondering whether the type coercion is safe? Well the short answer is no, it might not be. However, as you’ll see shortly, one of the reasons why we don’t expose either a public constructor on the Behaviour class, nor expose the collection of Behaviours directly is to ensure that this type coercion is always valid.
Next up is the NavigationRoutes class, which is essentially just a wrapper around a collection of Behaviour instances.
public class NavigationRoutes
{
private IList<Tuple<Type, IApplicationBehaviour>> Behaviours { get; } = new List<Tuple<Type, IApplicationBehaviour>>();
public NavigationRoutes Register<T, THandler>(Action<T, THandler> init, Action<T, THandler> deinit, THandler action)
{
Behaviours.Add(new Tuple<Type, IApplicationBehaviour>(typeof(T), Behaviour.Create(init, deinit, action)));
return this;
}
public void Wire(object page)
{
var typeOfPage = page.GetType();
var behaviours = Behaviours.Where(x => x.Item1 == typeOfPage).Select(x=>x.Item2);
foreach (var behaviour in behaviours)
{
behaviour.Init(page);
}
}
public void Unwire(object page)
{
var typeOfPage = page.GetType();
var behaviours = Behaviours.Where(x => x.Item1 == typeOfPage).Select(x => x.Item2);
foreach (var behaviour in behaviours)
{
behaviour.Deinit(page);
}
}
}
You might be wondering why we didn’t just use a Dictionary. The answer is so that we can support multiple Behaviour definitions per page. I’m also certain there are more optimal ways to structure the Wire and Unwire methods but they’ll do for what we need right now. They simply iterate through the collection of behaviours and invoke the Init or Deinit method on behaviours that are registered for the specified page.
We also need to define an instance of the NavigationRoutes class, which for the moment we’ll place in App.xam.cs.
public NavigationRoutes Routes { get; } = new NavigationRoutes()
.Register<MainViewModel, EventHandler>(
(vm, act) => vm.ViewModelDone += act,
(vm, act) => vm.ViewModelDone -= act,
(s, e) => (Window.Current.Content as Frame).Navigate(typeof(SecondPage)))
.Register<SecondViewModel, EventHandler>(
(vm, act) => vm.ViewModelDone += act,
(vm, act) => vm.ViewModelDone -= act,
(s, e) => (Window.Current.Content as Frame).GoBack());
As you can see from this code we’re registering the ViewModelDone on both MainViewModel and SecondViewModel. For the MainViewModel we’re registering an Action that navigates to SecondPage. For the SecondViewModel we’re registering an Action that calls GoBack on the Frame.
The last thing to do is to intercept the Navigated event on the Frame in order to wire/unwire the behaviours.
private object PreviousPage { get; set; }
private void OnNavigated(object sender, NavigationEventArgs e)
{
if (PreviousPage != null)
{
Routes.Unwire((PreviousPage as Page).DataContext);
PreviousPage = null;
}
PreviousPage = e.Content;
Routes.Wire((PreviousPage as Page).DataContext);
}
Here you can see why we needed the Init and Deinit methods on the IApplicationBehaviour interface to be Action<object> – The Content property on the NavigationEventArgs is simply an object which we are casting it to a Page and extracting the DataContext, which is also untyped. Note that again, this is very rough at this point and obviously needs some null checking before it would be considered fit for use in production.
Testing Navigation Logic
Whilst we’ve successfully abstracted the navigation logic away from the view models, it’s still very closely tied to platform implementation. By this I mean that the actions we’ve registered rely on having a reference to the Frame and they specify the actual navigation action to carry out eg Navigate(typeof(MainPage)) or GoBack. If we wanted to write tests to validate our navigation logic, we can’t easily, unless they were UI tests that literally tested the behaviour of the application (I’m not saying these aren’t important, they’re just not something we can write as unit tests).
The next step in our journey is to put in place an abstraction of what we mean by navigation so that we can replace the Navigate and GoBack method calls with something that can be tested. If we look to existing mvvm frameworks for suggestions, we’ll remember that they typically pass a navigation service into the viewmodels. What if we do something similar – we create a navigation service interface that can be passed into our Actions. Of course, this will then require a per-platform implementation for how each navigation method should be carried out.
This sounds simply but the first issue we’ll come up against is that the Navigate method for UWP takes a type parameter being the type of the page to navigate to. If we’re abstracting navigation away from the UI platform, we need to define navigation based on types that aren’t associated with any UI platform (i.e. not MainPage or SecondPage). The logical conclusion is that in order to navigate to SecondPage, we should simply attempt to navigate to SecondViewModel and let the platform implementation worry about how to translate this to SecondPage.
Let’s start by defining the interface for our INavigationService. At this stage I’m not going to place any type constraints on the TViewModel since one of our goals is to avoid imposing a particular base class or interface on the view models we define.
public interface INavigationService
{
Task Navigate<TViewModel>();
Task GoBack();
}
Next up, the implementation of the NavigationService for Windows (UWP/Uno).
public class WindowsNavigationService:INavigationService
{
private Frame NavigationFrame { get; }
private NavigationRoutes Routes { get; }
public IDictionary<Type, Type> ViewModelToPageMap { get; } = new Dictionary<Type, Type>();
public WindowsNavigationService(Frame navigationFrame, NavigationRoutes routes)
{
NavigationFrame = navigationFrame;
NavigationFrame.Navigated += OnNavigated;
Routes = routes;
}
public async Task GoBack()
{
NavigationFrame.GoBack();
}
public async Task Navigate<TViewModel>()
{
NavigationFrame.Navigate(ViewModelToPageMap[typeof(TViewModel)]);
}
public WindowsNavigationService RegisterForNavigation<TPage, TViewModel>() where TPage : Page
{
ViewModelToPageMap[typeof(TViewModel)] = typeof(TPage);
return this;
}
private object PreviousPage { get; set; }
private void OnNavigated(object sender, NavigationEventArgs e)
{
if (PreviousPage != null)
{
Routes.Unwire((PreviousPage as Page).DataContext);
PreviousPage = null;
}
PreviousPage = e.Content;
Routes.Wire(this,(PreviousPage as Page).DataContext);
}
}
There’s three main sections to the implementation. Firstly, as you’d expect the constructor is expecting a Frame, which will be used to implement the Navigate and GoBack methods. In order to call Navigate on the Frame there is a translation between the TViewModel type parameter on the Navigate method to the type of Page to navigate to. This is done by looking up the ViewModelToPageMap dictionary. This leads us to the second section, which is the RegisterForNavigation method that simply adds a mapping into the ViewModelToPageMap dictionary. It might seem weird that we’re returning the instance of the WindowsNavigationService but this is simply to allow for a more fluent way of calling the RegisterForNavigation method, which we’ll see shortly.
The last section of the implementation is actually code we’ve seen before, which simply wires and unwires the behaviours as the Frame navigates between pages. This was previously in the App.xaml.cs but makes sense to be incorporated into the WindowsNavigationServices.
In the App.xaml.cs, rather than attaching an event handler to the Navigated event on the rootFrame, we’re instead going to create an instance of the WindowsNavigationService and call the RegisterForNavigation method for each page/view model pair we have.
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
var navService = new WindowsNavigationService(rootFrame, Routes)
.RegisterForNavigation<MainPage, MainViewModel>()
.RegisterForNavigation<SecondPage, SecondViewModel>();
The last thing we need to do is to change the implementation of the NavigationRoutes class in order to leverage the INavigationService. So far as part of registering each behaviour we’ve avoided placing any constraints on the event or the action that’s passed into the Register method. The type of the event in the init and deinit methods (i.e. THandler) simply has to match the type of the Action. The challenge with wanting to pass in the INavigationService is that we risk enforcing some sort of constraint on THandler. For example we could require THandler to inherit, or be an instance of, EventHandler<INavigationService>. If we did this, all of a sudden we’re leaking the concept of navigation back into our view model.
The work around for this is that instead of passing in an Action into the register method, we’re going to pass a function that accepts an INavigationService and returns an Action. Essentially this is a sneaky way for us to wrap an instance of the INavigationService in a way that makes it accessible to the Action, without affecting the signature of the Action itself. You can see from the following code that the signature of the event and Action is still EventHandler.
private NavigationRoutes Routes { get; } = new NavigationRoutes()
.Register<MainViewModel, EventHandler>(
(vm, act) => vm.ViewModelDone += act,
(vm, act) => vm.ViewModelDone -= act,
(nav) => (s, e) => nav.Navigate<SecondViewModel>())
.Register<SecondViewModel, EventHandler>(
(vm, act) => vm.ViewModelDone += act,
(vm, act) => vm.ViewModelDone -= act,
(nav) => (s, e) => nav.GoBack());
Now that I’ve given the endgame away, let’s take a quick look at the implementation. Firstly, the Behaviour implementation has changed. Due to an increase in complexity, it now makes sense to capture the init, deinit and actionFactory parameters. The public interface for IApplicationBehaviour has also been updated.
public class Behaviour<T, THandler> :IApplicationBehaviour
{
private Action<T, THandler> Init { get; set; }
private Action<T, THandler> Deinit { get; set; }
private Func<INavigationService, THandler> ActionFactory { get; set; }
private T attachedEntity;
private THandler action;
public void Attach(INavigationService navService, object entity)
{
if(attachedEntity!=null)
{
Detach();
}
action = ActionFactory(navService);
attachedEntity = (T)entity;
Init(attachedEntity, action);
}
public void Detach()
{
if (attachedEntity == null)
{
return;
}
Deinit(attachedEntity, action);
}
private Behaviour() { }
public static Behaviour<T, THandler> Create(Action<T, THandler> init, Action<T, THandler> deinit,Func<INavigationService, THandler> actionFactory)
{
return new Behaviour<T, THandler>()
{
Init = init,
Deinit = deinit,
ActionFactory=actionFactory
};
}
}
public interface IApplicationBehaviour
{
void Attach(INavigationService navService, object entity);
void Detach();
}
Then there’s the implementation of NavigationRoutes
public class NavigationRoutes
{
private IList<Tuple<Type, IApplicationBehaviour>> Behaviours { get; } = new List<Tuple<Type, IApplicationBehaviour>>();
public NavigationRoutes Register<T, THandler>(Action<T, THandler> init, Action<T, THandler> deinit, Func<INavigationService,THandler> actionFactory)
{
Behaviours.Add(new Tuple<Type, IApplicationBehaviour>(typeof(T), Behaviour<T,THandler>.Create(init, deinit, actionFactory)));
return this;
}
public void Wire(INavigationService navigationService, object page)
{
var typeOfPage = page.GetType();
var behaviours = Behaviours.Where(x => x.Item1 == typeOfPage).Select(x=>x.Item2);
foreach (var behaviour in behaviours)
{
behaviour.Attach(navigationService, page);
}
}
public void Unwire(object page)
{
var typeOfPage = page.GetType();
var behaviours = Behaviours.Where(x => x.Item1 == typeOfPage).Select(x => x.Item2);
foreach (var behaviour in behaviours)
{
behaviour.Detach();
}
}
}
The main change here is really the Register method signature and that we’re calling Attach and Detach instead of Init and Deinit.
Ok, so we have the basics of a platform agnostic navigation protocol (I’m trying to avoid the overloaded use of framework – what we’ve built is just a couple of classes that help abstract navigation, it’s definitely not a framework…. just yet).
At the beginning I stated that we’d look at the implementation for other platforms but rather than draw this post out any further, let’s list a couple of things for a future post that we need to look at:
- Implementation of INavigationService for Xamarin.Forms, WPF and WinUI (UWP and/or Desktop)
- Passing parameters as part of navigation
- Returning values as part of navigating back
- Multi-window and potentially multi-region support
Would love feedback on this – check out the repo on github: https://github.com/nickrandolph/mvvmnavigation
Nice!
So, when can we expect to see part 2 of this?
Regards
Hi Tobias,
Apologies, it’s coming… just been busy with a few other posts. Do you have suggestions on where you’d like to see this go, and what you feel should come next?
Hi Nick!
Thanks for your reply!
Pretty much what you have already stated, in a simple, understandable and clean way, mvvm:
Implementation of INavigationService for WinUI (UWP and/or Desktop)
Passing parameters as part of navigation. Nullable int to load the correct object or create new if null.
Returning values as part of navigating back.
Just Basic navigation.
I have only worked with wpf mvvm, prism before and uwp seams to be pretty different.
Thanks!
Uno platform by the way, if that’s different from pure UWP.
I don’t know whether you saw it but there’s support for UWP/Uno in the latest version of Prism!
How do you handle navigation deeper in the hierarchy of view models? e.g. companies/123/invoices/456.
If you’re just going page to page, then that shouldn’t be an issue. Where the proposed model is a little simplistic is if you have nesting of views (eg a page with a list of items AND details).
I have implemented a similar use case where instead of having a single navigator responsible for the routes, we have a navigator stack and each time a navigation-aware view is loaded, it would push its navigator on the stack. The navigations service, owning the stack, would simply use the top of the stack for deciding where to navigate.