Not all the WPF applications are huge. A very few are still used as utilities, installers and simple tools to achieve a specific task. Navigation is very trivial in applications. PRISM supports a very nice navigation framework. To develop such simple WPF applications, developers really hesitate to use big frameworks like PRISM, Caliburn Micro, etc.

So I thought of develop a simple helpers which achieve navigation in small MVVM applications without need of any enterprise frameworks. Let us develop a simple application looks like below, using this simple navigation model.

Download the sample and you will find a Navigation library with simple helper classes.

navigation

 

 

 

 

 

 

 

 

 

Declare regions in the shell, where the views needs to be injected at run time. Following is the way to declare a region in XAML.

<ContentControl
nav:NavigationRegion.RegionName="{x:Static constants:RegionNames.MainRegion}" />

This ContentControl will act as a region and views will be injected as content. NavigationService is a static class which contains the following methods.

  • NavigateTo (Method which helps to inject a view into specific region)
  • GoBack (Method helps to navigate back to previous view)
  • CanGoBack (Method decides whether the region has the ability to go back)
  • ClearViews (Method used to clear all views from the region)

NavigateTo method accepts two parameters, the region name and the view object. The NavigationService will keep a record of registered regions. Also it keep track of views history in a stack.

Here is how navigate and go back will work,

    public class ShellViewModel
{
public ShellViewModel()
{
NavigationService.NavigateTo(RegionNames.HeaderRegion, new HeaderView(new HeaderViewModel()));
NavigationService.NavigateTo(RegionNames.NavigationRegion, new NavigationView(new NavigationViewModel()));
NavigationService.NavigateTo(RegionNames.MainRegion, new FirstView());
}
}

The back button in the header region will be disabled, if there is no possibility for back navigation.

        public DelegateCommand<object> BackCommand
{
get
{
return new DelegateCommand<object>(this.OnGoBack, this.CanGoBack);
}
}

private void OnGoBack(object obj)
{
NavigationService.GoBack(RegionNames.MainRegion);
}

private bool CanGoBack(object arg)
{
return NavigationService.CanGoBack(RegionNames.MainRegion);
}

Download Sample

Happy Coding!!!