Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button in action bar for Xamarin.Forms application?

Is there an Xamarin.Forms way of adding a button to the actionbar/navigation item (without resorting to platform specific code) ?

like image 390
NeoDarque Avatar asked Apr 06 '15 19:04

NeoDarque


2 Answers

If by action bar/navigation you mean the navigation bar at the top you can use this method:

private void ShowToolbar()
{
if (Device.OS == TargetPlatform.iOS)
{
    // move layout under the status bar
    this.Padding = new Thickness(0, 20, 0, 0);

    toolbarItem = new ToolbarItem("Sync", "sync_icon.png", () =>
    {
        //if (!response)
        //{
        //    response = true;
        SyncService();
        //}
        //else
        //    return;
    }, 0, 0);
    ToolbarItems.Add(toolbarItem);
}

if (Device.OS == TargetPlatform.Android)
{

    toolbarItem = new ToolbarItem("Sync", "sync_icon.png", () =>
    {
        //if (!response)
        //{
        SyncService();
        //}
        //else
        //    return;
    }, 0, 0);
    ToolbarItems.Add(toolbarItem);

}

if (Device.OS == TargetPlatform.WinPhone)
{
    toolbarItem = new ToolbarItem("Sync", "sync_icon.png", () =>
    {
        //if (!response)
        //{
        //    response = true;
        SyncService();
        //}
        //else
        //    return;
    }, 0, 0);
    ToolbarItems.Add(toolbarItem);
    }
}
like image 125
Mario Galván Avatar answered Oct 29 '22 07:10

Mario Galván


In MainPage.xaml, you may add the following code.

<ContentPage.ToolbarItems>
    <ToolbarItem Text="Click Me!" Icon="iconName.png" Clicked="ToolbarItem_Clicked"/>
</ContentPage.ToolbarItems>

Now, in the MainPage.xaml.cs, click handler should be added.

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private async void ToolbarItem_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new NewPage());
    }
}

For Navigation to occur, the constructor in App.xaml.cs should contain following code.

public App()
    {
        InitializeComponent();
        MainPage = new NavigationPage(new MainPage());
    }
like image 30
20B2 Avatar answered Oct 29 '22 05:10

20B2