Reputation: 289
I'm building an UWP app with a navigationview. When I click on my navigation item I want to change my frame. It's really easy to do this without MVVM but I prefer a solution with MVVM.
My Frame is "ContentFrame". Now I want to use a navigationservice. The classic way to do this is:
public class NavigationService : INavigationService
{
public void NavigateTo(Type viewType)
{
Frame rootFrame = Window.Current.Content as Frame;
rootFrame.Navigate(viewType);
}
public void NavigateBack()
{
Frame rootFrame = Window.Current.Content as Frame;
rootFrame.GoBack();
}
}
But for my use case the "Window.Current.Content" should be replaced with the Frame from my HomePage. I've no idea how I can access this through MVVM.
My project is on a public git: https://github.com/stefmorren/AutoClicker/tree/Devel
You can do a push request if it's easier.
Upvotes: 1
Views: 3265
Reputation: 39072
First add a public property of type Frame
to your HomePage
:
public Frame NavigationFrame => ContentFrame;
Now, your HomePage
is currently inside a root Frame
. To get to it, you will have to use it's Content
property:
public class NavigationService : INavigationService
{
public void NavigateTo(Type viewType)
{
var rootFrame = Window.Current.Content as Frame;
var homePage = rootFrame.Content as HomePage;
homePage.NavigationFrame.Navigate(viewType);
}
public void NavigateBack()
{
var rootFrame = Window.Current.Content as Frame;
var homePage = rootFrame.Content as HomePage;
homePage.NavigationFrame.GoBack();
}
}
To simplify this a bit more, you could even remove the rootFrame
altogether. In App.xaml.cs
you have to update your code to create the HomePage
directly:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
HomePage page = Window.Current.Content as HomePage;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (page == null)
{
page = new HomePage();
Window.Current.Content = page;
}
if (e.PrelaunchActivated == false)
{
// Ensure the current window is active
Window.Current.Activate();
}
}
And you would now use the following to access the NavigationFrame
property:
public class NavigationService : INavigationService
{
public void NavigateTo(Type viewType)
{
var homePage = Window.Current.Content as HomePage;
homePage.NavigationFrame.Navigate(viewType);
}
public void NavigateBack()
{
var homePage = Window.Current.Content as HomePage;
homePage.NavigationFrame.GoBack();
}
}
Now HomePage
is directly the Content
of your Window
, so we can access it via Window.Current.Content
.
Upvotes: 5