Search code examples
uwpnavigationview

Item selection in NavigationView


In NavigationView I have 3 Items. If user click on the second button I would like to clean form and redirect (for example with MainFrame.Navigate(typeof(BlankPage1));) to the first Item. Redirect works fine but NavigationViewItem's selection stay on the second NavigationViewItem. The same code:

nvTopLevelNav.SelectedItem = nvTopLevelNav.MenuItems[index];
(nvTopLevelNav.SelectedItem as NavigationViewItem).IsSelected = true;

does not help. Is there any way to change selection?

By the way, if for navigation I use MainPage (MainFrame.Navigate(typeof(MainPage));) I will get the second Menu with correct selection. For me it looks like object is not correct refreshed. Could you please clarify?


Solution

  • You can try to use the NavigationView's Tapped event to change its SelectedItem. See the following code.

    Xaml:

    <NavigationView x:Name="nvTopLevelNav" Tapped="nvTopLevelNav_Tapped" .../>
    

    Code Behind:

    private void nvTopLevelNav_Tapped(object sender, TappedRoutedEventArgs e)
    {
        Debug.WriteLine(nvTopLevelNav.SelectedItem);
        NavigationViewItem ItemContent = nvTopLevelNav.SelectedItem as NavigationViewItem;
        if (ItemContent != null)
        {
            switch (ItemContent.Tag)
            {
                case "Nav_BlankPage1":
                    MainFrame.Navigate(typeof(BlankPage1));
    
                    break;
                case "Nav_BlankPage2":
                    MainFrame.Navigate(typeof(BlankPage1));
                    MyItem = nvTopLevelNav.MenuItems.ElementAt(0) as NavigationViewItem;
                    nvTopLevelNav.SelectedItem = MyItem;
                    break;
                case "Nav_BlankPage3":
                    MainFrame.Navigate(typeof(BlankPage3));
                    break;
                case "Nav_Settings":
                    break;
            }
        }
    }