uwpnavigationfocusuwp-xamlwindows-template-studio

How to avoid the first navigationview item focused when opening?


I'm using Windows Template Studio, and created a NavigationView.

My original thought is creating a navigatoin menu like Android, when pressing the Left button in a page, open the navigation menu, and focus on the corresponding item.

For example, When I'm in Settings page, and current focus in on a Button. When I press Left button, the NavigationView opens and focus on the Settings item.

But now the focus always on the first item, and then go to the corresponding item.

Here is the repo that can reproduce the bug, you can run it on pc/xbox.

You can see the video here.

So how to avoid the first navigationview item focused when opening?

enter image description here


Solution

  • This seems to be a default behavior, because the focus of your NavigationViewItem is set manually, before setting the focus of a specific item, it does not prevent the default focus behavior of NavigationView, like this:

    1. Open NavigationView
    2. The application automatically focuses on MenuItems (the first item is automatically selected)
    3. You reset the focus of the option in the PaneOpened event.

    This operation will indeed cause a focus jump. In order to avoid this, we need to judge when the first item gets focus (using strNaviTag as a reference):

    ShellPage.xaml

    <winui:NavigationViewItem x:Uid="Shell_Main" Icon="People" Tag="main" helpers:NavHelper.NavigateTo="views:MainPage" GettingFocus="FirstItem_GettingFocus"/>
    

    ShellPage.xaml.cs

    private void OnItemInvoked(WinUI.NavigationView sender, WinUI.NavigationViewItemInvokedEventArgs args)
    {
        // ...
        (Application.Current as App).strNaviTag = item.Tag.ToString();
        // ...
    }
    
    
    private void NavigationViewItem_GettingFocus(UIElement sender, GettingFocusEventArgs args)
    {
        if((Application.Current as App).strNaviTag != "main" 
            && !(args.OldFocusedElement is Microsoft.UI.Xaml.Controls.NavigationViewItem))
        {
            args.TryCancel();
            return;
        }
    }
    

    This prevents the first item from gaining focus when the requirements are not met.

    Thanks.