How to show ToolbarItem only for iOS in Xamarin.Forms?

I'm devolpin an app with Xamarin.Forms for iOS and Android and I have a page that I want show ToolbarItem only for iOS app. In Android, I want use a button inside of page. How can I do that? I made it adding a ToolbarItem with blank text in Android, but I believe that is not the right way to do that.

Here is my page xaml code:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
         prism:ViewModelLocator.AutowireViewModel="True"
         x:Class="VFood.Views.Garcons">

<ContentPage.Content>
    <StackLayout>
        <Label Text="Garçons"
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>
<ContentPage.ToolbarItems>
    <OnPlatform x:TypeArguments="ToolbarItem">
        <OnPlatform.iOS>
            <ToolbarItem Text="Adicionar"/>
        </OnPlatform.iOS>
        <OnPlatform.Android>
            <ToolbarItem Text=""/>
        </OnPlatform.Android>
    </OnPlatform>
</ContentPage.ToolbarItems>

Upvotes: 1

Views: 1684

Answers (2)

VahidShir
VahidShir

Reputation: 2126

I too got null reference exception doing that in XAML, what worked for me however is doing that in code-behind:

public partial class Garcons
{
    public Garcons()
    {
        InitializeComponent();
        if (Device.RuntimePlatform == Device.iOS)
        {
            var myToolbarItem = new ToolbarItem()
            {
                Icon = "myIcon.png",
                Order = ToolbarItemOrder.Primary,
                Priority = 0,
                Text = "MyToolbarItem"
            };

            myToolbarItem.SetBinding(MenuItem.CommandProperty, "MyToolbarItemCommand");
            ToolbarItems.Insert(0, myToolbarItem);
        }
    }
}

The above code is equivalent of this XAML version:

<ToolbarItem Icon="myIcon.png" Order="Primary" Priority="0"
  Text="MyToolbarItem" Command="{Binding MyToolbarItemCommand}"/>

Upvotes: 1

Jason
Jason

Reputation: 89214

don't specify anything for the platform you DON'T want to have it

<ContentPage.ToolbarItems>
    <OnPlatform x:TypeArguments="ToolbarItem">
        <OnPlatform.iOS>
            <ToolbarItem Text="Adicionar"/>
        </OnPlatform.iOS>
    </OnPlatform>
</ContentPage.ToolbarItems>

Upvotes: 1

Related Questions