Windowstemplatestudio: How to invoke NavigationView.MenuItems added dynamically

Created on 28 Apr 2019  路  6Comments  路  Source: microsoft/WindowsTemplateStudio

I'm using WTS, navigation pane type, code behind mode. Currently, the NavigationViewItems are added in xaml file, and hard coded.

        <winui:NavigationView>
            <winui:NavigationView.MenuItems>
                <winui:NavigationViewItem x:Uid="Shell_Main" Icon="Home" helpers:NavHelper.NavigateTo="views:MainPage" />
            </winui:NavigationView.MenuItems>
            <Grid>
                <Frame x:Name="shellFrame" />
            </Grid>
        </winui:NavigationView>

Now I want to add some more items in code behind, so I create:

    private void RenderNavigationViewMenu()
        {
            foreach(var item in (Application.Current as App).globalCategoryCollection)
            {
                WinUI.NavigationViewItem navigationViewItem = new WinUI.NavigationViewItem();
                navigationViewItem.Content = item.name;
                navigationViewItem.Icon = new FontIcon { Glyph = "\uE74C" };
                navigationView.MenuItems.Add(navigationViewItem);
            }
        }

How to write code in event OnItemInvoked and Frame_Navigated, to navigate to a corresponding page?
A related repo is here.

Can Close Out Soon Developer Question

All 6 comments

@hupo376787 The generated code is looking for an attached property to use in the navigation. You can set this in your repo by adding the line below.

            for(int i = 0; i < 5; i++)
            {
                WinUI.NavigationViewItem navigationViewItem = new WinUI.NavigationViewItem();
                navigationViewItem.Content = "AAA " + i.ToString();
+               NavHelper.SetNavigateTo(navigationViewItem, typeof(APage));
                navigationView.MenuItems.Add(navigationViewItem);
            }

Great, thanks. I think a description in the code-behind file about how to add menu items using .cs code will be very helpful and friendly.

Great idea

Verified in dev-nightly:
Templates version: 0.20.19190.1
Wizard version: 0.20.19190.1

Thanks guys for your great work.

Thank you for your contribution!!

Was this page helpful?
0 / 5 - 0 ratings