1

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

Vincent
  • 3,124
  • 3
  • 21
  • 40

1 Answers1

3

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.

Richard Zhang
  • 7,523
  • 1
  • 7
  • 13
  • This solution almost solved my requirement, except when the focus is on my first page(Main), and open the `NavigationView` menu. Do you have any better improvement? – Vincent May 13 '20 at 03:23
  • Hello, I noticed that in `App.xaml.cs`, `strNaviTag` defaults to an empty string, you can set it to "main". – Richard Zhang May 13 '20 at 04:03
  • It's the same. I think it's because we wrote `strNaviTag != "main" ` in 'NavigationViewItem_GettingFocus'. – Vincent May 13 '20 at 04:46
  • `strNaviTag` is a basis for judgment, but it seems that there are still some shortcomings. Our solution is to prevent the default behavior of `NavigationView` when it is opened (select the first item). On this basis, you can create a more appropriate judgment condition according to your needs. – Richard Zhang May 13 '20 at 04:55