in c++ winrt NavigationView how do I select an item after control is populated dynamically

74 Views Asked by At

I am using WinUi 2.8 and I have a navigation view that is populated dynamically using MenuItemsSource Property:

<muxc:NavigationView x:Name="mainNav" MenuItemsSource="{x:Bind FirstLvelItems, Mode=OneWay}"
                     MenuItemTemplate="{StaticResource NavigationViewMenuItem}" >

An item has children also populated dynamically:

<DataTemplate x:Key="NavigationViewMenuItem" x:DataType="local:MyType">
      <muxc:NavigationViewItem x:Name="NavItem"  Content="{x:Bind DisplayName}"  MenuItemsSource="{x:Bind SecondLevelItems}" Tag="{x:Bind Name}"/>
</DataTemplate>

After control is loaded I want to select an item that I know for sure that is on the second level. I use NavigationView.Loaded() event and there I can find the parent (the first level) of my wanted item (using ContainerFromMenuItem() ) but I can not find the item from the second level. I tried using ContainerFromMenuItem(), MenuItems(), VisualTreeHelper but nothing works.

I am using Winrt in an island from a Win32 app so I can not give a sample project.

1

There are 1 best solutions below

0
Alexandru Dragomir On

In WinUI, NavigationViewItem is not expanded by default, so it's MenuItems won't be loaded when the NavigationView control is loaded.

You can set the NavigationViewItem IsExpanded to true in xaml. This way, the NavigationViewItems on the second level will be loaded when NavigationView Loaded event is triggered.

<DataTemplate x:Key="NavigationViewMenuItem" x:DataType="local:MyType">
      <muxc:NavigationViewItem IsExpanded="True" x:Name="NavItem"  Content="{x:Bind DisplayName}"  MenuItemsSource="{x:Bind SecondLevelItems}" Tag="{x:Bind Name}"/>
</DataTemplate>

PS: On NavigationView Loaded event handler you need to collapse the NavigationViewItems you don't want to be expanded.