---
# System prepended metadata

title: UWP ナビゲーションビュー（Windows.UI.Xaml.Controls.NavigationView）　2021-04-13
tags: [Windows.UI.Xaml.Controls, UWP, NavigationView]

---

---
lang: ja-jp
breaks: true
---
# UWP ナビゲーションビュー（Windows.UI.Xaml.Controls.NavigationView）　2021-04-13

> NavigationView
> https://docs.microsoft.com/ja-jp/windows/uwp/design/controls-and-patterns/navigationview

> UWP - NavigationView Controll の使い方
> https://blog.beachside.dev/entry/2018/06/22/210000

### 環境
* Microsoft Visual Studio Professional 2017 15.9.34
* Windows Server 2019 1809
* Microsoft.NETCore.UniversalWindowsPlatform 6.2.8

## ナビゲーションビュー
![](https://i.imgur.com/Oe5rEeU.png)



### MainPage.xaml
```xaml=
<Page
    x:Class="App3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App3"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <NavigationView
            x:Name       ="NavView"
            Canvas.ZIndex="0"
            ItemInvoked  ="NavView_ItemInvoked"
            Loaded       ="NavView_Loaded"
            BackRequested="NavView_BackRequested"
            >

            <NavigationView.MenuItems>
                <NavigationViewItem x:Uid="HomeNavItem" Content="ホーム" Tag="home">
                    <NavigationViewItem.Icon>
                        <FontIcon Glyph="&#xE10F;"/>
                    </NavigationViewItem.Icon>
                </NavigationViewItem>
                <NavigationViewItemSeparator/>
                <NavigationViewItemHeader Content="メインページ"/>
                <NavigationViewItem x:Uid="AppsNavItem"  Icon="AllApps" Content="アプリ" Tag="apps" />
                <NavigationViewItem x:Uid="GamesNavItem" Icon="Video"   Content="ゲーム" Tag="games"/>
                <NavigationViewItem x:Uid="MusicNavItem" Icon="Audio"   Content="音楽"   Tag="music"/>
            </NavigationView.MenuItems>

            <NavigationView.AutoSuggestBox>
                <AutoSuggestBox x:Name="SuggestBox" QueryIcon="Find"/>
            </NavigationView.AutoSuggestBox>

            <NavigationView.HeaderTemplate>
                <DataTemplate>
                    <Grid Margin="24,10,0,0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Style="{StaticResource TitleTextBlockStyle}"
                           FontSize="28"
                           VerticalAlignment="Center"
                           Text="Welcome to NavigationView Sample"/>
                        <CommandBar Grid.Column="1"
                            HorizontalAlignment="Right"
                            VerticalAlignment="Top"
                            DefaultLabelPosition="Right"
                            Background="{ThemeResource SystemControlBackgroundAltHighBrush}">
                            <AppBarButton Label="Refresh" Icon="Refresh"/>
                            <AppBarButton Label="Import" Icon="Import"/>
                        </CommandBar>
                    </Grid>
                </DataTemplate>
            </NavigationView.HeaderTemplate>

            <Frame x:Name="ContentFrame" Margin="24">
                <Frame.ContentTransitions>
                    <TransitionCollection>
                        <NavigationThemeTransition/>
                    </TransitionCollection>
                </Frame.ContentTransitions>
            </Frame>

        </NavigationView>
    </Grid>
</Page>

```

### MainPage.xmal.cs
```csharp=
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// 空白ページの項目テンプレートについては、https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x411 を参照してください

namespace App3
{
    /// <summary>
    /// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void NavView_Loaded(object sender, RoutedEventArgs e)
        {
            // MainPage.xaml で書いた MenuItems の下にさらにコードで MenuItems を追加したり...
            NavView.MenuItems.Add(new NavigationViewItemSeparator());
            NavView.MenuItems.Add(new NavigationViewItem() { Content = "コンテンツ", Icon = new SymbolIcon(Symbol.Folder), Tag = "content" });

            // home を選択
            var item = GetNavigationViewItem("home");
            NavView.SelectedItem = item;
            // frame に home を表示
            NavView_Navigate("home");

            ContentFrame.Navigated += On_Navigated;
        }

        private void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
        {
            if (args.IsSettingsInvoked)
            {
                ContentFrame.Navigate(typeof(SettingsPage));
            }
            else
            {
                // メソッドの引数 arg の args.InvokedItem は、メニューがクリックされたら、Content の値が飛んでくる。へー。
                var tag = sender.MenuItems.OfType<NavigationViewItem>()
                    .First(x => x.Content.ToString() == args.InvokedItem.ToString())
                    .Tag.ToString();

                NavView_Navigate(tag);
            }
        }

        private void NavView_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
        {

        }

        private NavigationViewItem GetNavigationViewItem(string tag)
        {
            return NavView.MenuItems.OfType<NavigationViewItem>().First(i => i.Tag.ToString() == tag);
        }

        private void On_Navigated(object sender, NavigationEventArgs e)
        {
            //NavView.IsBackEnabled = ContentFrame.CanGoBack;

            if (ContentFrame.SourcePageType == typeof(SettingsPage))
            {
                NavView.SelectedItem = NavView.SettingsItem as NavigationViewItem;
            }
            else
            {
                var tag = _pageContents[ContentFrame.SourcePageType];
                NavView.SelectedItem = GetNavigationViewItem(tag);
            }
        }

        private void NavView_Navigate(string tag)
        {
            var targetType = _pageContents.FirstOrDefault(c => c.Value.Equals(tag)).Key;
            if (targetType != null)
            {
                ContentFrame.Navigate(targetType);
            }
        }

        private static IReadOnlyDictionary<Type, string> _pageContents = new Dictionary<Type, string>()
        {
            {typeof(HomePage)    , "home"    },
            {typeof(AppsPage)    , "apps"    },
            {typeof(GamesPage)   , "games"   },
            {typeof(MusicPage)   , "music"   },
            {typeof(ContentPage) , "content" },
        };

    }
}
```

###### tags: `UWP` `NavigationView` `Windows.UI.Xaml.Controls`
