Home > Net >  Xamarin.Forms Can you open a tab with a button?
Xamarin.Forms Can you open a tab with a button?

Time:05-10

I'm new to Xamarin.Forms and am making a home-page menu for my app which already has tabs to go different pages.

For the sake of presentation for a new user of the app, I wish to have big buttons on the home page which also go to some of these specific tabs. This example currently shows my attempt with opening the 'About' tab page.

The current code will attempt to push a modal of the About page from the ICommand (Which actually opens up a white screen instead of loading the actual page. I don't know why yet.), but I would like it to open the tab instead. Is this possible in Xamarin.Forms?

public class HomePageViewModel : BaseViewModel
    {
        public HomePageViewModel()
        {
            Title = "Home Page";
            OpenAboutCommand = new Command(async () => await Application.Current.MainPage.Navigation.PushModalAsync(new AboutViewModel()));         
        }

        public ICommand OpenAboutCommand { get; }
    }

CodePudding user response:

You could try the code below.

Xaml:

 <Button Command="{Binding OpenAboutCommand}"></Button>

Code behind: TabbedPage3 is my tabbedpage. 1 is the index for the tabs of tabbedpage3. Please note that the index could not over the tabs.

public partial class Page5 : ContentPage
{
    public Page5()
    {
        InitializeComponent();
        this.BindingContext = new Page5ViewModel();
    }
}
public class Page5ViewModel
{
    public ICommand OpenAboutCommand { get; set; }
    public Page5ViewModel()
    {
        OpenAboutCommand = new Command(() =>
        {
            var tab = new TabbedPage3();
            tab.CurrentPage = tab.Children[1];

            Application.Current.MainPage.Navigation.PushModalAsync(tab);
        });

    }
}

CodePudding user response:

As it turns out, there's already a method Xamarin.Forms mentions that does this very thing once you add it as a route in AppShell.xaml.

Here is the XAML for AppShell.Xaml. Notice the Route="AboutPage".

 <ShellContent Route="AboutPage" x:Name="aboutPage" Title="About" Icon="icon_about.png" ContentTemplate="{DataTemplate local:AboutPage}" />

And now for the cs code. (Everyone appreciates a good one liner.)

public class HomePageViewModel : BaseViewModel
    {
        public HomePageViewModel()
        {
            Title = "Home Page";
            OpenAboutCommand = new Command(() => { Shell.Current.GoToAsync("//AboutPage");});
        }

        public ICommand OpenAboutCommand { get; }
    }
  • Related