You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中如何仅在MacCatalyst平台显示MenuBarItems?

仅在MacCatalyst平台显示MAUI MenuBarItems的最优方案

不需要在ViewModel中添加额外属性,直接用MAUI的OnPlatform标记就能实现仅在指定平台渲染MenuBarItems,这是更简洁的原生方案:

<ContentPage.MenuBarItems>
    <OnPlatform x:TypeArguments="MenuBarItemCollection">
        <On Platform="MacCatalyst">
            <MenuBarItem Text="File">
                <MenuFlyoutItem Text="Exit"
                                Command="{Binding ExitCommand}" />
            </MenuBarItem>
            <MenuBarItem Text="{lang:Translate Title}">
                <MenuFlyoutSeparator />
                <MenuFlyoutItem Text="{lang:Translate Add}"
                                Command="{Binding AddLocationCommand}" />
            </MenuBarItem>
            <MenuBarItem Text="View">
                <MenuFlyoutItem Text="Refresh"
                                Command="{Binding RefreshCommand}" />
            </MenuBarItem>
        </On>
    </OnPlatform>
</ContentPage.MenuBarItems>

方案说明

  • OnPlatform的x:TypeArguments指定为MenuBarItemCollection,匹配ContentPage.MenuBarItems的类型
  • 仅在Platform="MacCatalyst"的On节点内编写菜单代码,其他平台会自动忽略这部分内容
  • 相比ViewModel属性绑定的方式,这种写法更直接,不需要额外的平台判断逻辑,完全在XAML中完成平台差异化渲染,减少ViewModel的冗余代码

内容的提问来源于stack exchange,提问作者Enrico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:32:09