首页 > 解决方案 > 使用嵌套框架导航

问题描述

这是我的问题情况的简化示例。

主页.xaml

<page
    ...
    xmlns:helpers="using:MyNamespace.Helpers"
    xmlns:views="using:MyNamespace.Views"
    ...>

    <NavigationView Name="MainNav"
                    PaneDisplayMode="LeftCompact"
                    ...>
        <NavigationView.MenuItems>
            <NavigationViewItem Content="OtherPage"
                                helpers:NavHelper.NavigateTo="views:OtherPage">
                </NavigationViewItem>
                ... other NavigationViewItem's...
        </NavigationView.MenuItems>

        <Frame Name="MainFrame".../>   
</page>

MainPage.xaml.cs

namespace MyNamespace
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            MainNav.ItemInvoked += Navigate.NavView_ItemInvoked;
        }
        ...
    }
}

OtherPage.xaml - 在视图文件夹中

<page
    ...
    xmlns:helpers="using:MyNamespace.Helpers"
    xmlns:views="using:MyNamespace.Views"
    ...>

    <NavigationView Name="OtherNav"
                    PaneDisplayMode="Top"
                    ...>
        <NavigationView.MenuItems>
            <NavigationViewItem Content="Other Page"
                                helpers:NavHelper.NavigateTo="views:OtherPage_1">
                </NavigationViewItem>
                ... other NavigationViewItem's...
        </NavigationView.MenuItems>

        <Frame Name="OtherFrame".../>   
</page>

其他页面.xaml.cs

namespace MyNamespace.Views
{
    public sealed partial class OtherPage : Page
    {
        public OtherPage()
        {
            this.InitializeComponent();
            OtherNav.ItemInvoked += Navigate.NavView_ItemInvoked;
        }
        ...
    }
}

Navigate.cs - 在服务文件夹中

namespace MyNamespace.Services
{
    static class Navigate
    {
        public static void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
        {
            \\ do some navigation logic
            ...
            private _frame = ???;
            ...

            _frame.Navigate(_page, null, transitionInfo);
        }

好的,在所有示例代码之后,这是我的问题。在NavView_ItemInvoked事件处理程序中,我需要能够_frame根据NavigationViewItem被调用进行设置;要么MainFrame要么OtherFrame

注意:我可能会远离我的应用程序中的嵌套框架,但我首先想弄清楚这一点,因为我不想浪费学习机会。

标签: c#xamluwpnavigation

解决方案


触发 ItemInvoked 事件时,可以从中获取 NavigationView 实例。NavigationView 有一个Content属性,它实际上代表了当前触发的 navigationView 中的 Frame。因此可以通过 Frame.name 获取 MainFrame 或OtherFrame

static class MyNavigate
    {​
        public static void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)​
        {​
            Frame currentFrame = sender.Content as Frame;​
            String name = currentFrame.Name;​
            if (name == "OtherFrame")​
            {​
                currentFrame.Navigate(.......);​
            }​
            else {​
                currentFrame.Navigate(.......);​
            }​
        }​
    }

推荐阅读