I am writing an windows 10 UWP app and want to use the NavigationView in combination with the BackRequested
event handler to handle back navigation, however "GoBack" doesn't update the selected menu item, this means when I use the backbutton the selected menu item doesn't change. to fix this I have created an ugly foreach loop that selects the MenuItem
on back navigation using a tag. This works but I was wondering if there is a more elegant way to do this,
GoBack
doesn't fire the ItemInvoked
or SelectionChanged
event so I can't seem to be able to use those.
MainPage.xaml
<NavigationView x:Name="NavView"
CompactModeThresholdWidth="1920" ExpandedModeThresholdWidth="1920"
ItemInvoked="NavView_ItemInvoked"
SelectionChanged="NavView_SelectionChanged"
Loaded="NavView_Loaded"
Canvas.ZIndex="0">
<NavigationView.MenuItems>
<NavigationViewItem x:Uid="HomeNavItem" Content="Home" Tag="home">
<NavigationViewItem.Icon>
<FontIcon Glyph=""/>
</NavigationViewItem.Icon>
</NavigationViewItem>
<NavigationViewItemSeparator/>
</NavigationView.MenuItems>
<NavigationView.HeaderTemplate>
<DataTemplate>
<Grid Margin="24,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource TitleTextBlockStyle}"
FontSize="28"
VerticalAlignment="Center"
Text="Welcome"/>
</Grid>
</DataTemplate>
</NavigationView.HeaderTemplate>
<Frame x:Name="ContentFrame" Margin="24">
<Frame.ContentTransitions>
<TransitionCollection>
<NavigationThemeTransition/>
</TransitionCollection>
</Frame.ContentTransitions>
</Frame>
</NavigationView>
MainPage.xaml.cs snippet:
public MainPage()
{
this.InitializeComponent();
// initial page for ContentFrame
ContentFrame.Navigate(typeof(HomePage));
ContentFrame.Navigated += MainFrame_Navigated;
SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
}
private void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
{
string tag = null;
if (!ContentFrame.CanGoBack) return;
e.Handled = true;
ContentFrame.GoBack();
if (ContentFrame.SourcePageType == typeof(HomePage))
{
tag = "home";
}
foreach (var navViewMenuItem in NavView.MenuItems)
{
if (navViewMenuItem is NavigationViewItem item)
{
if (item.Tag.Equals(tag)) item.IsSelected = true;
}
}
}
private void MainFrame_Navigated(object sender, NavigationEventArgs e)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = ((Frame) sender).CanGoBack
? AppViewBackButtonVisibility.Visible
: AppViewBackButtonVisibility.Collapsed;
}