我正在构建一个带导航视图的UWP应用程序。当我点击我的导航项目时,我想要更改我的框架。没有MVVM这样做很容易,但我更喜欢使用MVVM的解决方案。
我的相框是“ContentFrame”。现在我想使用导航服务。 这样做的经典方法是:
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();
}
}
但是对于我的用例,“Window.Current.Content”应该替换为我的HomePage中的Frame。我不知道如何通过MVVM访问它。
我的项目是公开的git:https://github.com/stefmorren/AutoClicker/tree/Devel
如果更容易,您可以执行推送请求。
答案 0 :(得分:3)
首先将Frame
类型的公共属性添加到HomePage
:
public Frame NavigationFrame => ContentFrame;
现在,您的HomePage
目前位于根Frame
内。要实现它,您必须使用它的Content
属性:
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();
}
}
为了简化这一点,您甚至可以完全删除rootFrame
。在App.xaml.cs
中,您必须更新代码才能直接创建HomePage
:
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();
}
}
现在,您将使用以下内容访问NavigationFrame
属性:
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();
}
}
现在HomePage
直接是Content
的{{1}},因此我们可以通过Window
访问它。