Xamarin.Forms UWP平台ToolBarItems显示省略号,如何实现自动展开?
解决Xamarin.Forms UWP平台ToolBarItems显示为省略号的问题
嘿,这个问题我之前做Xamarin.Forms跨平台项目时也踩过坑!UWP默认会把导航栏的ToolBarItems塞进溢出菜单(就是那个省略号按钮),哪怕导航栏空间足够也可能出现这种情况。下面给你两个亲测有效的解决办法:
方法一:使用平台特定代码(推荐)
Xamarin.Forms针对UWP提供了专门的平台属性,可以直接禁用导航栏的动态溢出功能,让所有ToolBarItems直接显示在导航栏上。
在XAML中设置:
先添加UWP平台特定的命名空间:
xmlns:uwp="clr-namespace:Xamarin.Forms.PlatformConfiguration.WindowsSpecific;assembly=Xamarin.Forms.Core"
然后在ContentPage标签上添加属性:
<ContentPage ... uwp:NavigationPage.IsToolbarDynamicOverflowEnabled="False"> <!-- 页面内容 --> <ContentPage.ToolbarItems> <ToolbarItem Text="你的按钮文本" IconImageSource="icon.png" Command="{Binding YourCommand}" /> </ContentPage.ToolbarItems> </ContentPage>
在代码后台设置:
如果习惯用代码控制,可以在页面构造函数里添加:
using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.WindowsSpecific; public YourPage() { InitializeComponent(); // 针对UWP平台禁用动态溢出 On<Windows>().SetToolbarDynamicOverflowEnabled(false); }
方法二:自定义UWP渲染器
如果平台特定代码不生效,还可以通过自定义渲染器强制设置每个ToolBarItem的溢出模式为Never,确保它们始终显示在导航栏上。
步骤1:在UWP项目中创建自定义渲染器
using Xamarin.Forms.Platform.UWP; using YourAppNamespace; // 替换成你的应用命名空间 using YourAppNamespace.UWP; // 替换成你的UWP项目命名空间 using Windows.UI.Xaml.Controls; [assembly: ExportRenderer(typeof(ContentPage), typeof(CustomContentPageRenderer))] namespace YourAppNamespace.UWP { public class CustomContentPageRenderer : PageRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e) { base.OnElementChanged(e); if (Control != null && Element is Xamarin.Forms.ContentPage page) { // 获取UWP原生的CommandBar if (Control.Content is Frame frame && frame.Content is Page uwpPage) { if (uwpPage.TopAppBar is CommandBar commandBar) { // 遍历所有导航栏按钮,强制设置不进入溢出菜单 foreach (var cmd in commandBar.PrimaryCommands) { if (cmd is AppBarButton appBarBtn) { appBarBtn.OverflowMode = CommandBarOverflowMode.Never; } } } } } } } }
问题原因说明
UWP的CommandBar默认启用了动态溢出功能,当它判断导航栏空间不足时(有时候即使空间足够也会误判),就会把按钮移到省略号菜单里。上面的两种方法,要么直接关闭动态溢出,要么强制按钮不进入溢出菜单,都能解决你的问题。
附上你提供的场景截图:

内容的提问来源于stack exchange,提问作者Ankur Gupta
相关产品推荐
相关产品推荐

