简体   繁体   中英

Adding ToolbarItems to MainPage.xaml.cs in a Xamarin.Forms Project

As described in the title I am looking to add a ToolbarItem to my MainPage.xaml.cs in a Xamarin.Forms Project.

This is because I want an Actionbar on my Android App.

This to my knowledge is available on a NavigationPage.

I have not been able to set my Mainpage as a NavigationPage despite many attempts, it appears it will not let me set it as anything other than a ContentPage.

So far the best information I can find on this subject is here:

xamarin.forms not showing ToolbarItem

This however does not answer my question as it is relevant to App.xaml.cs not MainPage.xaml.cs

And my project is a multi-platform Xamarin.Forms for building apps apps for IOS and Android with Xamarin and Xamarin.Forms project.

Currently however I'm just focusing on Android in the shared C# project (MainPage.xaml.cs).

Thanks in Advance.

The ToolbarItems needs a Navigation Page to show them up. So modify your MainPage wrapped by a navigation page:

App.xaml.cs:

  public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage(new MainPage());
    }

Screenshot: 在此处输入图片说明

As Described in Wendy's answer the following code is required:

MainPage = new NavigationPage(new MainPage());

However she forgot the mention this code needs to be added to App.xaml.cs not MainPage.xaml.cs file.

This file is present in the C# Project for a Xamarin.Forms mobile app.

You can find it by clicking the drop down arrow in the 'Solution Explorer' on the 'App.xaml' file to find the 'App.xaml.cs' file.

If you can't find it type it in the search bar on the 'Solution Explorer'.

And edit the MainPage = new MainPage(); code in the file to MainPage = new NavigationPage(new MainPage());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM