question

JamieColclough-7785 avatar image
0 Votes"
JamieColclough-7785 asked JarvanZhang-MSFT commented

Xamarin Forms - How to implement ViewModel navigation in a TabbedPage

I've followed the following tutorial to replace page navigation in my Xamarin Forms application with view model-first navigation:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/navigation

This has worked fine for all cases in my app in which I programatically navigate to a page, as I can just navigate to the ViewModel now. However, the main page of my app is a TabbedPage. I believe these pages work by automatically creating a page when you click on the corresponding tab, which is page-first navigation.
How could the TabbedPage be edited so that when I click on a tab, the ViewModel is navigated to, which then brings the page into the TabbedPage?
Or is this outside the remit of view model-first navigation and so no changes need to be made?



dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

Hello,​

Welcome to our Microsoft Q&A platform!

How could the TabbedPage be edited so that when I click on a tab, the ViewModel is navigated to, which then brings the page into the TabbedPage

Hi, JamieColclough. You could get the tabbedPage in the viewModel class first. Then get the child page collection of the tabbedPage via TabbedPage.Children property and change the value of CurrentPage to perform the navigation.

var tabbedPage = App.Current.MainPage as TestTabbedPage;
tabbedPage.CurrentPage = tabbedPage.Children[index];

Best Regards,

Jarvan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 6
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi Jarvan,
This looks promising,
How would I overwrite the tabbed page so when I click on the tab it uses a custom method that what you've described instead of the default?

0 Votes 0 ·

overwrite the tabbed page so when I click on the tab it uses a custom method

For this function, try to detect the CurrentPageChanged of the tebbedPage to customize the event.

0 Votes 0 ·

At this point though, the page has already changed hasn't it? so doing the viewmodel-first navigation at this point wouldn't be worth it. What I need is a way to intercept the click of the tabbar, cancel the default page navigation, find out which button was clicked and use that to find the ViewModel to navigate to.


0 Votes 0 ·
Show more comments