【问题标题】:[UWP][MVVM] Navigate in a frame in a window[UWP][MVVM] 在窗口中的框架中导航
【发布时间】:2018-04-01 09:34:28
【问题描述】:

我正在构建一个带有导航视图的 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”应该替换为我主页中的框架。我不知道如何通过 MVVM 访问它。

我的项目在公共 git 上:https://github.com/stefmorren/AutoClicker/tree/Devel

如果更容易的话,你可以做一个推送请求。

【问题讨论】:

    标签: c# mvvm uwp


    【解决方案1】:

    首先将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 直接是你的WindowContent,所以我们可以通过Window.Current.Content 访问它。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多