【问题标题】:How to show ToolbarItem only for iOS in Xamarin.Forms?如何在 Xamarin.Forms 中仅为 iOS 显示 ToolbarItem?
【发布时间】:2018-08-22 02:02:16
【问题描述】:

我正在使用适用于 iOS 和 Android 的 Xamarin.Forms 开发一个应用程序,并且我有一个页面,我希望仅为 iOS 应用程序显示 ToolbarItem。在 Android 中,我想在页面内使用一个按钮。我怎样才能做到这一点?我在 Android 中添加了一个带有空白文本的 ToolbarItem,但我认为这不是正确的方法。

这是我的页面 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>

【问题讨论】:

    标签: xaml xamarin xamarin.forms


    【解决方案1】:

    不要为您不想拥有的平台指定任何内容

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

    【讨论】:

    • 应用程序崩溃并出现“对象引用未设置为对象的实例”错误
    【解决方案2】:

    我在 XAML 中也遇到了 null 引用 异常,但对我有用的是在代码隐藏中这样做:

    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}"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多