Search code examples
c#xamluwp-xamlwinui-3

How to change the Content and IsSelected properties of a NavigationViewItem in WinUI 3 by locating it using its x:name or tag?


I create some NavigationViewItem and set its x:Name and Tag, like:

<NavigationView x:Name="nvSample"
                SelectionChanged="nvSample_SelectionChanged"
                IsBackButtonVisible="Collapsed"
                IsSettingsVisible="False">

        <NavigationView.MenuItems>

            <NavigationViewItem x:Name="NavigationViewItem_HomePage" Icon="Home" Content="Home" Tag="HomePage" IsSelected="True" />
            <NavigationViewItem x:Name="NavigationViewItem_SimpleSortPage" Icon="Sort" Content="Sort" Tag="SimpleSortPage" />

            <...........>

        </NavigationView.MenuItems>

</NavigationView>

I want to find the NavigationViewItem object by its x:Name or Tag so that I can change Content and IsSelected property by code.

I find Type.GetType may get a page by x:Name, like:

Type pageSelected = Type.GetType("NumberSort.Pages.SimpleSort");
RootPageFrame.Navigate(pageSelected,this);

So I tried to use it to get the NavigationViewItem object, like:

var NavigationItem = (NavigationViewItem)Type.GetType("NavigationViewItem_HomePage");

However, its doesn't work.


Solution

  • I found a easy way to do that:

    public static void SwitchPage (string pageName,NavigationView navigationView)
    {
    
        var navigationViewItems = navigationView.MenuItems.OfType<NavigationViewItem>().ToList();
    
        if (navigationViewItems != null) {
            foreach (var item in navigationViewItems)
            {
                if( item.Tag.Equals(pageName))
                {
                    item.IsSelected = true; break;
                }
            }
        }
        else {throw new ArgumentNullException()};
    }
    

    In this example, it sets IsSelected property of NavigationViewItem as true, which pageName is equal with Tag property of NavigationViewItem.