我正在使用适用于iOS和Android的Xamarin.Forms开发一个应用程序,并且我有一个页面,我希望仅针对iOS应用程序显示ToolbarItem。在Android中,我想在页面中使用一个按钮。我该怎么做?我让它在Android中添加了一个带有空白文本的工具栏项,但我相信这不是正确的方法。
这是我的页面 xaml 代码:
<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>
不要为您不想拥有的平台指定任何内容
<ContentPage.ToolbarItems>
<OnPlatform x:TypeArguments="ToolbarItem">
<OnPlatform.iOS>
<ToolbarItem Text="Adicionar"/>
</OnPlatform.iOS>
</OnPlatform>
</ContentPage.ToolbarItems>
在 XAML 中这样做我也得到了空引用异常,但是对我有用的是在代码隐藏中执行此操作:
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);
}
}
}
上面的代码等效于此 XAML 版本:
<ToolbarItem Icon="myIcon.png" Order="Primary" Priority="0"
Text="MyToolbarItem" Command="{Binding MyToolbarItemCommand}"/>