uwpwindows-template-studio

How to modify navigation menu in main.cs while using WindowsTemplateStudio?


I'm using WindowsTemplateStudio, For some reason, I have to modify navigation menu in MainPage.xaml.cs, like remove or add some items. How to do? Thx.


Solution

  • If you created a Navigation Pane via WindowsTemplateStudio, you can find the NavigationView in Views/ShellPage.xaml where you can add a NavigationViewItem.

    In the NavigationViewItem, x:Uid points to the text resource in Strings/en-us.

    If necessary, you can also add shortcuts in ShellPage.xaml.cs.


    Update

    If you want to modify the NavigationView in the ShellPage on other pages, you need to do some extra work.

    1. Set the NavigationView's x:FieldModifier property to Public
    <winui:NavigationView
        x:Name="navigationView"
        x:FieldModifier="Public"
        ...>
    </winui:NavigationView>
    
    1. Create a static instance of ShellPage
    public static ShellPage Current;
    
    public ShellPage()
    {
        InitializeComponent();
        DataContext = this;
        Current = this;
        Initialize();
    }
    
    1. Complete the operation of NavigationView through ShellPage.Current.navigationView
    foreach (var item in ShellPage.Current.navigationView.MenuItems)
    {
        var navItem = item as NavigationViewItem;
        // Todo
    }
    

    Of course, this way can directly achieve the goal. But in comparison, I prefer to use Binding, generate MenuItems by creating ObservableCollection<T> and bind to navigationView.MenuItemsSource.

    Best regards.