Gilberto
Gilberto

Reputation: 77

NavigationView change selected item using back button

I'm using a navigationview control in a UWP app, the thing is when I click the back button the focused element doesn't change to the item displayed in the contentframe. For example the clicked elements were camara, store, musica, then back button twice to display camara in the contentframe element, but musica still has the focus (blue rectangle)

private void FrameNavigated( object sender, NavigationEventArgs e )
    {
        var currentView = SystemNavigationManager.GetForCurrentView();
        if ( ContentFrame.CanGoBack )
        {
            currentView.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
        }
        else
        {
            currentView.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
        }
    }

private void OnBackRequested( object sender, BackRequestedEventArgs e )
    {
        if ( ContentFrame.CanGoBack )
        {
            e.Handled = true;

            PageStackEntry pageStackEntry = ContentFrame.BackStack.LastOrDefault();

            ContentFrame.GoBack();

            if ( pageStackEntry != null )
            {
                string nombre = pageStackEntry.SourcePageType.Name;
                MenuItem item = subItemsMenu.FirstOrDefault(nom => nom.NombrePantalla.Equals(nombre));

                navView.SelectedItem = item;
                navView.Header = item.Encabezado;
            }
        }
    }

enter image description here

Upvotes: 1

Views: 636

Answers (2)

Gilberto
Gilberto

Reputation: 77

Solved, using NavigationViewExtensions.SetSelectedIndex(NavigationView, index); from Microsoft.Toolkit.Uwp.UI.Extensions 4.0.0, since 5.0.0 version is deprecated

Upvotes: 3

Canhua Li
Canhua Li

Reputation: 319

I didn't see any problem in your code. Several ways may help to troubleshooting:

  1. Debug and make sure MenuItem item is not null.

  2. When back button is clicked, try select home or camera directly by your code

    private void OnBackRequested( object sender, BackRequestedEventArgs e ) { string nombre = "Camera"; MenuItem item = subItemsMenu.FirstOrDefault(nom => nom.NombrePantalla.Equals(nombre)); navView.SelectedItem = item; }

  3. Add SelectionChanged="nav_SelectionChanged" to the XAML and then check SelectionChanged

  4. Post a simple app which can repro your problem

Upvotes: 0

Related Questions