[UWP] [MVVM]在窗口中的框架中导航

时间:2018-04-01 09:34:29

标签: c# mvvm uwp

我正在构建一个带导航视图的UWP应用程序。当我点击我的导航项目时,我想要更改我的框架。没有MVVM这样做很容易,但我更喜欢使用MVVM的解决方案。

enter image description here

我的相框是“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

如果更容易,您可以执行推送请求。

1 个答案:

答案 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访问它。