MAUI中如何仅在MacCatalyst平台显示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
相关产品推荐
相关产品推荐

