WPF Navigating Views From Other Views

Recently, a user left a comment on one of my YouTube videos asking a very common question: “is it possible to change the view with a button from ur current view(e.g from blue to red with a button in the red view ) without using the buttons on the menu bar?” In relation to my video this was in response to, doing this task is slightly more complicated. Being able to change your windows view, from the controls of other views, requires a bit of MVVM. Which it is fairly clear that, the video this comment was made on, does not strictly follow MVVM. Accomplishing the ability to navigate to other views, from within other views, requires the knowledge of multiple things: Commands, Binding, Observable Objects, Generics etc. Eh, Well, it doesn’t strictly require knowledge on those things. There are several ways you could go about developing this, but those are the things required for the way I will be presenting an example. The good news is, I have videos covering them all!

For now, I will simply be providing a GitHub link to a project I whipped together. This project will display how this is implemented. I may be inclined to do a video on it, but because of school I am unsure where I would have the time to do it.

Here is the basic idea.

We want to create a MainViewModel, inside of this we will hold a ViewModel property. As we use binding UserControls in my current video, we must instead bind the UserControl to the ViewModel property. Doing this, we can then simply change the ViewModel property to change the views. Here is the catch: Since our ViewModels will be children of our MainViewModel, we have to find a effective way to make calls back to it’s parent to change its context(i.e. it’s ViewModel property). We could do this with dependency injection from the the MainViewModel to each and ever child ViewModel, but to a degree this will get messy. By utilizing a BaseViewModel class, Generics, Relay Commands and INotifyPropertyChanged we can accomplish this.

 

I have commented the code in some of the classes to reference you to videos that cover their implementations.

GitHub Example(Click Here)

Leave a Reply

Your email address will not be published. Required fields are marked *