xamluwpuwp-xamlwindows-template-studio

Windows UI Library - how to invoke NavigationView.MenuItems added dynamically


I'm using windows ui library and windows template studio. Currently, the winui:NavigationView.MenuItems are added in xaml.

    <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>

And Now I add some more items in .cs code.

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

How to write code, when I click the added item, app navigate to the related page. A related repo is here.

enter image description here


Solution

  • The default configuration of windows template studio is applying an attached property(helpers:NavHelper.NavigateTo) for per NavigationViewItem.

    <winui:NavigationViewItem x:Uid="Shell_Main" Icon="Document" helpers:NavHelper.NavigateTo="views:MainPage" />
    

    So, if you want to create the NavigationViewItem in code-behind, you still need to apply the attached property for every NavigationViewItem like the following:

    WinUI.NavigationViewItem navigationViewItem = new WinUI.NavigationViewItem();
    navigationViewItem.Content = "AAA " + i.ToString();
    navigationViewItem.SetValue(NavHelper.NavigateToProperty, typeof(Views.APage));