Search code examples
c#windowsuwpuwp-xaml

How to determine the current page a frame is displaying in UWP


I'm quite new to UWP development, and so far I followed the tutorial below to make the a program that navigates through pages using a NavigationView to select and a Frame to load the pages. But I wanted to fix a tiny issue: when I go back pages, the selected page on NavigationView does not update.

I just wanted a way to determine the current page the Frame is displaying to select the respective page in NavigationView, and this would be triggered with the back button.

My code to go back pages is currently this:

private void NavView_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
{
    if (ViewFrame.CanGoBack)
        ViewFrame.GoBack();
}

And what I wanted to do is:

private void NavView_BackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
{
    if (ViewFrame.CanGoBack)
        ViewFrame.GoBack();

    var currentFrameName = Frame.getCurrentPage // gets the current page name
    
    // iterates thru NavigationMenu items until the same as displayed is found
    foreach(NavigationViewItemBase item in NavView.MenuItems) 
    {
        if (item is NavigationViewItem && item.Tag.ToString() == currentFrameName.toString())
        {
        NavView.SelectedItem = item;
        break;
        }
    }
}

Since the NavigationMenu items have the same tag name as the pages.

I haven't found a function to get the right name yet. The ones I used so far only displayed the current page the frame is inserted (MainPage), like Frame.CurrentSourcePageType.ToString() and Frame.Content.ToString(). I'm using Debug.WriteLine(), from System.Diagnostics namespace, as output (maybe this is the issue?). Any help?


Solution

  • I haven't found a function to get the right name yet.

    I'm not sure if the name you mentioned is the type of the Page or the name of the Page.

    If you are trying to get the type of the current page. You could use Page.GetType() to get the type. Like this:

     var page = MyFrame.Content as Page;
     var type = page.GetType();
     if (type.Name.Equals("BlankPage1")) 
     {
      // do what you want.
     }
    

    If you are trying to the name of the current Page of the frame. You could try @Rayomnd Chen's suggestion to assign a name to the Page first.

    Xaml:

    <Page
    x:Class="TestGetPage.BlankPage1"
    .....
    x:Name="MyBlankPage"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    

    Code:

      var page = MyFrame.Content as Page;
    
      if (page.Name.Equals("MyBlankPage")) 
      {
          // do what you want
      }