4
votes

So I've seen that a Navigation Service exists in WPF for maintaining a flow through an application. I'm not really in the market for the back and forward type functionality. I'm just looking for a good way to switch between Views when a button on a particular view is pressed. I'm using MVVM, so I'm not sure if I can let the App.xaml.cs possibly contain a copy of each View or ViewModel and let a ViewModel command call into App.xaml.cs to do the switching. Perhaps I should just handle the Click event on the button and do some flavor of this.Close(); NewWindow.Show();.
As with many things in WPF, this one is not intuitive to me although there probably are a couple simple solutions.

Thanks!

2
Are you using any app frameworks like Prism? Are you using IoC or anything like that? That'll help decide an approach.Anderson Imes
no unity, IoC, or anything. I'm trying to stick to MVVM, but this is a standalone app with four different windows that can be switched to from one another.Bob

2 Answers

2
votes

I created a "window loader" class that the app class instantiates when the application starts. The window loader has a dictionary that maintains an association of view model types and view types. It also has a method that takes a view model instance, resolves the view based on the view model's type, instantites the view, sets the view's datacontext to the view model then shows it. The window loader also registers for an event in the view model which is raised when the window wants to close.

The window loader implements an IWindowLoader interface and a reference to it is kept in each view model (when the window loader instantiates a view model it assigns itself to a public IWindowLoader property in the view model). So any view model can cause any other view model to be shown without knowing about views and without doing the showing itself. Also, the window loader can easily be mocked for testing.

When I went through the same process you are now, I found lots of examples of this same basic pattern. I just ended up rolling my own.

2
votes

A way to solve this is to introduce Controllers which are responsible for the workflow of the application. They create, show and close multiple views in the application.

How this works can be seen in the sample applications of the WPF Application Framework (WAF) project.