2010
04.14
VN:F [1.9.10_1130]
Rating: 8.4/10 (14 votes cast)


How do you go from one view to another without coupling views or view models together? Here is how I am currently doing it.

The source code is available here

The overall application design layout

The layout we are after is an outlook style navigation where there is a fixed layout template onto which all the application views will be rendered. It will therefore be possible for developers to create their own views and show them within the applications predetermined layout. The layout splits the views into two sections : The navigation section on the left and the main section on the right. These two sections form one atomic view and we want both to be bound to the same view model. The navigation content on the left allows us to change settings or select items that affect the display in the main content on the right.

Lets go into expression blend and create a new project. I’m going to create a simple stock trading application which initially contains just the following:

MainWindow.xaml
NavigationControl.xaml
MainView.xaml
PortfolioView.xaml
StockQuoteView.xaml

the main view layout

the main view layout

I have created a view that consists of a Grid with three rows and three columns, a status bar, a menu, a grid splitter and my own NavigationControl. I have placed the controls in the appropriate grid row and column positions.
Note the decision the create a separate control for the Navigation aspect of the main view. The behaviour of the navigation is clearly a separate concern to that of the main view and so this should be encapsulated into a separate control. This will enable the navigation behaviour to be easily swapped for a more elaborate, more engaging navigation control later on for example. This also serves to limit the complexity of the main view XAML.

You may be asking yourself why I did not choose to make the menu also a separate control. The simple answer is : No reason at all. In fact it would probably be a better idea to do that however for the purposes of simplicity I chose not to go down that route because I will be defining each command that the menu is bound to as a separate member of the underlying view model and so there would be nothing much to gain in terms simplicity or less lines of XAML overall. However if I decided that all the commands would be served up by one IEnumerable property on the underlying view model from which I would dynamically create the menu items then this would then be a good reason to isolate that behaviour into a separate DynamicMenuControl for example. Another reason to create a separate control would be if I thought that the menu structure was going to be extensive and therefore it would benefit from having the menu defined in a separate file. The same goes for the status bar and any other control for that matter. Either way this is still obeying PMVVM and so the rest is just an implementation detail.

Here is the XAML for the main view:

<Grid x:Name="LayoutRoot">
		<Grid.ColumnDefinitions>
			<ColumnDefinition Width="0.2*"/>
			<ColumnDefinition Width="Auto"/>
			<ColumnDefinition Width="0.8*"/>
		</Grid.ColumnDefinitions>
		<Grid.RowDefinitions>
			<RowDefinition Height="Auto"/>
			<RowDefinition/>
			<RowDefinition Height="Auto"/>
		</Grid.RowDefinitions>
		<GridSplitter HorizontalAlignment="Left" Width="5"
                      Grid.Column="1"
                      Grid.Row="1"/>
		<StatusBar Margin="0"
                   VerticalAlignment="Top"
                   Height="23"
                   Grid.ColumnSpan="3"
                   Grid.Row="2"/>
		<Menu Margin="0" Height="23" Grid.ColumnSpan="3">
			<MenuItem Header="Views">
				<MenuItem Header="Stock Quotes"
                          Command="{Binding Path=NavigateToStocksCommand}"/>
				<MenuItem Header="Portofolio"
                          Command="{Binding Path=NavigateToPortfolioCommand}"/>
			</MenuItem>
		</Menu>
		<local:NavigationControl
		Margin="0,-23,0,0"
		Grid.Row="1"
		DataContext="{Binding}"/>
		<ContentControl Margin="0"
		Content="{Binding Path=CurrentView}"
		d:LayoutOverrides="Width, Height"
		Grid.Row="1"
		Grid.Column="2"/>
	</Grid>

The next thing I need to do is set-up the initial window of the application. It is a good idea to have as fewer windows defined as possible and define their content in separate user controls. Windows are expensive to maintain as they contain repeated code and so a change to one will mean a change to all. For example say your application goes into test and the testers discover that no parent has been set on any of the pop up windows or that the window style is not correct and there should not be a maximise button. In this case you would need to find all your pop-ups and change their properties. Inheritance is an option but in this case composition over inheritance allows you to define just one window into which you can dynamically set the content at run time. You could just define a generic style for all your windows which solved this problem but then you have written countless windows and repeated code for nothing! With this in mind the MainWindow XAML looks like this:

<Window
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	x:Class="PMVVM.MainWindow"
	x:Name="Window"
	Title="MainWindow"
	Width="640" Height="480">
	<Grid x:Name="LayoutRoot">
		<ContentControl Content="{Binding}"/>
	</Grid>
</Window>

That’s it ! Ideally this is as much content as I would like to have in the main window.

At this point the other views don’t contain much more than a text block to illustrate that the view is different from the next. We will come back to the views later.

Lastly the Navigation control needs to provide some means of allowing the user to invoke the relevant commands:

<Grid x:Name="LayoutRoot">
		<Grid.RowDefinitions>
			<RowDefinition Height="Auto"/>
			<RowDefinition/>
			<RowDefinition Height="Auto"/>
			<RowDefinition Height="Auto"/>
		</Grid.RowDefinitions>
		<TextBlock
		Text="{Binding Path=Name}"
		TextWrapping="Wrap"
		d:LayoutOverrides="Height"/>
		<ContentControl
			Content="{Binding Path=CurrentView}" Grid.Row="1"/>
		<Button Grid.Row="2" Height="23"
		Content="Stock Quotes"
		Command="{Binding Path=NavigateToStocksCommand}"/>
		<Button
		Content="Portfolio" Grid.Row="3" Height="23"
		Command="{Binding Path=NavigateToPortfolioCommand}"/>
	</Grid>

Now I must temporarily take off my rather dusty designer hat and put on my developer hat. So I will open up the solution I created in blend in visual studio.

Application XAML in visual studio

Now I am about to introduce two very important aspects of PMVVM which, aside from the view models, are critical to its argument. They are : Commands and Dependency Injection. Commands allow us to interact with and communicate between view models in a decoupled way. Dependency injection facilitates this further by allowing us to deal with contracts (interfaces) rather than concrete implementations of our view models. Both these facilities enable the creation of an extremely flexible application.

Now first thing’s first lets create the contracts for our view models :

using System.Windows.Input;
namespace PMVVM.ViewModels
{
    public interface IMainViewModel : IViewModelBase{
        object CurrentView { get; }
        ICommand NavigateToStocksCommand { get; }
        ICommand NavigateToPortfolioCommand { get; }
        void NavigateToView(object viewToNavigate);
    }
}

namespace PMVVM.ViewModels
{
    public interface IStockQuotesViewModel :
             IViewModelBase{
        string Name { get; }
    }
}

using System.Collections.Generic;
namespace PMVVM.ViewModels
{
    public interface IPortofolioViewModel :
             IViewModelBase{
        string Name { get; }
        IEnumerable<string> Portfolios { get; }
    }
}

using System.ComponentModel;
namespace PMVVM.ViewModels
{
    public interface IViewModelBase :
             INotifyPropertyChanged{
    }
}

Note the empty IViewModelBase interface. I will be adding some members to that later on. But for now it will serve as the default implementation of our INotifyPropertyChanged interface.

Lets also look at the implementation of the MainViewModel which is the only implementation we are really interested in at this point:

using System.Windows.Input;
using PMVVM.Commands;
namespace PMVVM.ViewModels.Implementation
{
    public class MainViewModel : ViewModelBase,IMainViewModel{
        private object _currentView;
        public object CurrentView{
            get { return _currentView; }
            private set
            {_currentView = value;
                OnPropertyChanged("CurrentView");
            }
        }
        public ICommand NavigateToStocksCommand{
            get { return new NavigateToViewCommand(Container.Container.GetA<IStockQuotesViewModel>()); }
        }
        public ICommand NavigateToPortfolioCommand{
            get { return new NavigateToViewCommand(Container.Container.GetA<IPortofolioViewModel>()); }
        }
        public void NavigateToView(object viewToNavigate){
            CurrentView = viewToNavigate;
        }
    }
}

Here I have implemented the behaviour of the NavigateToView method and declared the navigation command properties that the designer was expecting would be present. Obviously we need to invoke NotifyPropertyChanged when the current view is changed.

So why have I created a method to set the current view and not exposed the setter in the interface? At the moment this appears to be nothing more than a coding style however the behaviour of navigation is unlikely to remain as just a setter of a property and so if we are following best practices we should not abuse the property setter by including behavioural code other than that associated with changing the state of that member. In our pursuit for clean code we also want to be explicit in our invocation so that the intent is clear when developers are reading the code.

The commands here are just subclasses of a variation of the RelayCommand that Microsoft endorses in the context of MVVM (online ref #1 Josh Smith on MVVM). For illustration purposes here it is :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
namespace PMVVM.Commands
{
    public abstract class WpfCommand : ICommand{
        private readonly string _verb;
        protected WpfCommand(string verb){
            _verb = verb;
        }
        public string Verb{
            get { return _verb; }
        }
        public void Execute(object parameter){
            RunCommand(parameter);
        }
        protected abstract void RunCommand(object parameter);
        protected abstract IEnumerable<string> GetPreconditions(object parameter);
        public bool CanExecute(object parameter){
            return GetPreconditions(parameter).Count() < 1;
        }
        public event EventHandler CanExecuteChanged{
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}

The verb parameter is not significant at this point but it will prove invaluable later on when we want to dynamically link commands to short-cuts or dynamically control the display text of commands in menu items for example.

Here is the navigation command subclass :

using System.Collections.Generic;
using PMVVM.ViewModels;
namespace PMVVM.Commands
{
    public class NavigateToViewCommand : WpfCommand{
        private readonly object _viewToNavigate;
        public NavigateToViewCommand(object viewToNavigate) : base("Navigate"){
            _viewToNavigate = viewToNavigate;
        }
        protected override void RunCommand(object parameter){
            Container.Container.GetA<IMainViewModel>().NavigateToView(_viewToNavigate);
        }
        protected override IEnumerable<string> GetPreconditions(object parameter){
            yield break;
        }
    }
}

The implementation of the container you see here is not important but you should be familiar with the concepts of dependency injection and inversion of control and perhaps look up the Windsor Container framework. Please refer to the source code for the implementation detail of the container framework I have implemented.

So what happens when we compile and run the solution? When we click the portfolio view button we see our portfolio view in both left and right panels. The same with the stock quote view. But this is not quite what we want is it? On the left we want to have a different view showing some controls the user can interact with and invoke changes that are displayed on the right.

Stock quote view

Stock quote view

So how do we do that? We create another view model with an elaborate system for communicating between the panels right? Wrong ! I mean you can do that if you like but it is not necessary! This is where we leverage the wonders of WPF and data templates. As far as the logical tree is concerned the view models for both left and right panels are the same and so they should be. Which brings me onto another argument of separating concerns: The navigation control needs to be told that its visual representation of the same view model must be different because it has a different purpose.

In the navigation control we need to add the following XAML:

    <UserControl.Resources>

        <DataTemplate DataType="{x:Type Implementation:StockQuotesViewModel}">
            <PMVVM:StocksQuoteNavigationView/>
        </DataTemplate>

        <DataTemplate DataType="{x:Type Implementation:PortofolioViewModel}">
            <PMVVM:PortfolioNavigationView/>
        </DataTemplate>

    </UserControl.Resources>

Here I am overriding the existing data templates for the view models with a different visual representation.

I now have the requirement for two more views that control the navigation aspect of each atomic view. Its OK for me to go ahead and create these however I will pass them on to the designer to actually implement them:

Portfolio view in expression blend

For illustration purposes I am only going to change the portfolio navigation view by adding a couple of TextBlocks and a ListBox so the user can select their portfolio. I will bind the list box to the list of portfolios on the underlying view model.

<Grid x:Name="LayoutRoot">
		<Grid.RowDefinitions>
			<RowDefinition Height="Auto"/>
			<RowDefinition Height="Auto"/>
			<RowDefinition/>
		</Grid.RowDefinitions>
		<TextBlock
		Text="{Binding Path=Name}" TextWrapping="Wrap"/>
		<ListBox Grid.Row="2"
		ItemsSource="{Binding Path=Portfolios}"/>
		<TextBlock HorizontalAlignment="Left"
		Text="Select a portfolio"
		TextWrapping="Wrap"
		d:LayoutOverrides="Height" Grid.Row="1"/>
	</Grid>

So now what happens when I compile and run the application?

Portfolio view in expression blend

VN:F [1.9.10_1130]
Rating: 8.4/10 (14 votes cast)
VN:F [1.9.10_1130]
Rating: +1 (from 3 votes)
Beginning a WPF/MVVM application: Navigating between views, 8.4 out of 10 based on 14 ratings

11 comments so far

Add Your Comment
  1. Hi. Nice one.. Thanks a lot.
    I couldnt see the source code available for download.

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: +1 (from 1 vote)
  2. Hi Stevie
    I’m just learning WPF and MVVM and I’m struggeling a bit with the navigation between views…..and stumbled across your blod…..very interesting, am trying to do something similar, but am at a loss :-((…..could you provide me with the source code for that example? that would help me a lot…..really like to learn how you did this…..that would be great!!!
    Thanks and Greetings from Switzerland
    Marc

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: 0 (from 0 votes)
  3. Any source code available?

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: -1 (from 1 vote)
  4. Guys, really sorry for not doing it sooner but the source code is now available as a link at the top of this blog entry. Enjoy…

    VN:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.10_1130]
    Rating: 0 (from 0 votes)
  5. just starting in WPF and looking at above. the link for source code no longer working and would really appreciate being able to get access to it to help me understand the whole MVVM set up as struggling

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: 0 (from 0 votes)
    • Sorry about that. I have updated the link and it should be working now.

      VN:F [1.9.10_1130]
      Rating: 0.0/5 (0 votes cast)
      VN:F [1.9.10_1130]
      Rating: 0 (from 0 votes)
      • thanks very much. appreciated, now to dig my way through it :)

        VA:F [1.9.10_1130]
        Rating: 0.0/5 (0 votes cast)
        VA:F [1.9.10_1130]
        Rating: 0 (from 0 votes)
  6. Hi,
    is it possible to have a tab and than render the views into different tab pages?
    After switching between tabs, the content and state of the views in the different tab pages should be preserved.
    Think about VS2010, you can edit different files and switch between them and never loos the edited content or the cursor posithen or what ever.

    Thanks

    Gerhard

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: 0 (from 0 votes)
    • Hi Gerhard,

      With a tab control the view state will be preserved by default because all the tab pages (TabItems) are part of the same visual tree. However the preservation of the state of your views should typically be the responsibility of the bound ViewModel. So using my example here, if I had a text box for example in one of my views, I would have a corresponding text field in the View Model. The corresponding View Model instance would be kept in memory. In the real world we do this using an IOC container. It’s better to retain the state of your views in ViewModels as ViewModels use fewer physical machine resources. Of course there may be situations where this may not be the best approach but it is my default stance. A secondary benefit of doing it that way is that it becomes easier to re-hydrate views between sessions.

      Steve

      VN:F [1.9.10_1130]
      Rating: 0.0/5 (0 votes cast)
      VN:F [1.9.10_1130]
      Rating: 0 (from 0 votes)
  7. Very Useful. Best example I have found for starting out with WPF/MVVM. Thanks a lot.

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: 0 (from 0 votes)
  8. Very good!
    your source work fine, but what about add a DataService to the viewmodels?
    How should i inject this service? (maybe adding a instance of DataService to ViewModelBase? )
    How i should call to my method at the moment to load the viewmodel? using other command?

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: 0 (from 0 votes)