user1820916
user1820916

Reputation: 169

Item selection in NavigationView

In NavigationView I have 3 Items. If user click on the second button I would like to clean form and redirect (for example with MainFrame.Navigate(typeof(BlankPage1));) to the first Item. Redirect works fine but NavigationViewItem's selection stay on the second NavigationViewItem. The same code:

nvTopLevelNav.SelectedItem = nvTopLevelNav.MenuItems[index];
(nvTopLevelNav.SelectedItem as NavigationViewItem).IsSelected = true;

does not help. Is there any way to change selection?

By the way, if for navigation I use MainPage (MainFrame.Navigate(typeof(MainPage));) I will get the second Menu with correct selection. For me it looks like object is not correct refreshed. Could you please clarify?

Upvotes: 2

Views: 2830

Answers (2)

Štefan Schindler
Štefan Schindler

Reputation: 187

Setting the SelectedItem using the Dispatcher has worked for me:

Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
    MainNavigationView.SelectedItem = MenuItem_Home;
});

The RunAsync method is used to execute code on the UI thread, but it can be called from the UI thread too.

Upvotes: 0

Breeze Liu - MSFT
Breeze Liu - MSFT

Reputation: 3808

You can try to use the NavigationView's Tapped event to change its SelectedItem. See the following code.

Xaml:

<NavigationView x:Name="nvTopLevelNav" Tapped="nvTopLevelNav_Tapped" .../>

Code Behind:

private void nvTopLevelNav_Tapped(object sender, TappedRoutedEventArgs e)
{
    Debug.WriteLine(nvTopLevelNav.SelectedItem);
    NavigationViewItem ItemContent = nvTopLevelNav.SelectedItem as NavigationViewItem;
    if (ItemContent != null)
    {
        switch (ItemContent.Tag)
        {
            case "Nav_BlankPage1":
                MainFrame.Navigate(typeof(BlankPage1));

                break;
            case "Nav_BlankPage2":
                MainFrame.Navigate(typeof(BlankPage1));
                MyItem = nvTopLevelNav.MenuItems.ElementAt(0) as NavigationViewItem;
                nvTopLevelNav.SelectedItem = MyItem;
                break;
            case "Nav_BlankPage3":
                MainFrame.Navigate(typeof(BlankPage3));
                break;
            case "Nav_Settings":
                break;
        }
    }
}

Upvotes: 1

Related Questions