WPF - Navigation
Premise
Over the past  few weeks, I was scrambling to develop a WPF 4.0 application along with a UI  designer who specializes in Expression Blend. Though I have worked on WPF 3.5  projects previously, I was really flummoxed while implementing fundamental  portions like navigation, modal pop-up’s, “Loading” animation, session  management, etc. in WPF. I am not saying that WPF 4.0 is vastly different from  WPF 3.5, but I realized that I have never closely worked with XAML and WPF  specifics like dependency properties, resource dictionaries, routed events,  etc.
Anyway, since  I had very limited time, I mostly chose the easiest ways to implement specific  areas of the application. In this post, I will describe the simplest method to  implement navigation in WPF.
Disclaimer
You might  have come across WPF architectural frameworks such as PRISM, MVVM, etc. I have  some experience with PRISM, but for my current application, I needed a "very  very basic” navigation mechanism. So I would not undermine or explain the pros  and cons of other WPF frameworks here.
Navigation
WPF – Navigation –  Basic
Steps:
1) Create a WPF window called Shell.xaml (or replace MainWindow.xaml). 
2) In App.xaml,  set the StartupUri  property to “Shell.xaml”  which is our navigation container.
3) As shown above, you may divide the Shell.xaml into Header, Body and Footer  portions. 
4) In the Body portion, place a ContentControl which holds  the content of various controls.
5) In Shell.xaml.cs, add the below  method:
public void LoadContent(UserControl ucShell)
{
ccShell.Content =  ucShell;
}
6) In App.xaml.cs,  add the below method:
public static void  LoadContent(UserControl  ucShell)
{
Shell shellWindow = (Shell)App.Current.MainWindow;
shellWindow.LoadContent(ucShell);
}
7) Now, you can create WPF user-controls as needed (say Login.xaml, Home.xaml, etc.)
8) In order to navigate between different user-controls, you  need to call App.LoadContent()  method and pass in the required user-control instance.
Notes:
#  You would call the App.LoadContent()  method inside the constructor of Shell.xaml.cs to load the initial view  like Login.xaml.
#  You could retain the user-control reference in Shell.xaml.cs or create new instances  as needed.
#  The Header and Footer portions of Shell.xaml could hide or  show elements (like Log out button) based on the current view. And you can add  more methods to App.xaml.cs to  achieve this behavior (like App.  IsLogoutVisible)
#  If you do not need  the Header and Footer portions, simply skip all the steps and use the App.Current.MainWindow.Content  property to set the view from any WPF user-control.
Hope this helps. Based on your  feedback, I plan to cover my other WPF learnings like modal pop-up’s, “Loading”  animation and session management in future posts. 

Comments