HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Navigation between pages in WPF MVVM application

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
applicationwpfnavigationmvvmbetweenpages

Problem

I did a project in WPF MVVM. Just a single Window with single Frame control and few Pages. My problem was communication between pages without not violating MVVM principles. I'd like to use all bestprogramming-practices.

Can you check if this code agrees with the all best principles?

My solution has two projects: WPF client, ViewModels PCL. I want to have my ViewModels separated from the Views.

Here is the code for WPF Client:

GitHub

App.xaml.cs

namespace NaviWPFApp
{
    using System.Windows;
    using NaviWPFApp.Views;
    using NaviWPFApp.Views.Pages;   

    public partial class App : Application
    {
        public static NavigationService Navigation; 

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);  

            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();  

            Navigation = new NavigationService(mainWindow.MyFrame);
            Navigation.Navigate();
        }
    }
}


App.xaml It's just:


    
        
    


I have one main window with frame, and two very similar pages (no code-behind):


    
        
    
   

    
        
    
 

    
        
    


I my client I have also two additional classes ViewModelLocator and NavigationService - used for naviation between pages:

```
namespace NaviWPFApp
{
using NaviWPFApp.ViewModels.Pages;

public class ViewModelLocator
{
public FirstPageViewModel FirstPageViewModel => new FirstPageViewModel(App.Navigation);
public SecondPageViewModel SecondPageViewModel => new SecondPageViewModel(App.Navigation);
}
}

namespace NaviWPFApp
{
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
using NaviWPFApp.ViewModels.Common;

public class NavigationService : INavigationService
{
readonly Frame frame;

public NavigationService(Frame frame)
{
this.frame = fram

Solution

My biggest concern is this: navigationService.Navigate("FirstPage"));
I pass view name as a string. That's because I don't want my ViewModel
knows anything about View. But my navigation service HAS TO KNOW about
View. That's why I did that interface with string parameter.

In a given design, independently from any implementation, a dependency either exist or not. Trying to solve this "problem" in the implementation is impossible.

You have to choose if your navigation service helps navigating through xaml views, or through some higher level, more abstract "navigation items".

Context

StackExchange Code Review Q#117968, answer score: 3

Revisions (0)

No revisions yet.