如何在.NET MAUI Shell中禁用FlyoutItem选中视觉状态(Windows平台)
解决方案:重写Windows平台Shell渲染器禁用选中状态
可以通过自定义Windows平台的Shell渲染器,修改底层WinUI NavigationViewItem 的 SelectsOnInvoked 属性为 false,从而完全消除点击MenuItem后的选中视觉提示。具体步骤如下:
1. 可选:创建自定义Shell类
如果需要针对性处理,可先定义一个继承自Shell的自定义类:
namespace YourAppNamespace; public class CustomShell : Shell { }
之后在App.xaml或App.xaml.cs中,将根控件替换为这个CustomShell即可。
2. 编写Windows平台自定义渲染器
在.NET MAUI的Windows头部项目中,添加以下渲染器类:
using Microsoft.Maui.Controls.Platform; using Microsoft.Maui.Controls.Platform.Windows; using Microsoft.UI.Xaml.Controls; using YourAppNamespace; [assembly: ExportRenderer(typeof(CustomShell), typeof(CustomShellRenderer))] namespace YourAppNamespace.WinUI; public class CustomShellRenderer : ShellRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Shell> e) { base.OnElementChanged(e); if (Control is NavigationView navigationView) { // 为NavigationViewItem设置样式,禁用点击选中 var itemStyle = new Microsoft.UI.Xaml.Style(typeof(NavigationViewItem)); itemStyle.Setters.Add(new Microsoft.UI.Xaml.Setter(NavigationViewItem.SelectsOnInvokedProperty, false)); navigationView.ItemContainerStyle = itemStyle; } } }
如果不需要自定义Shell,直接为默认Shell类型注册渲染器即可——将代码中的typeof(CustomShell)替换为typeof(Shell)。
补充说明
MAUI在Windows平台上使用WinUI的NavigationView渲染Shell的Flyout菜单,每个MenuItem对应一个NavigationViewItem。默认情况下SelectsOnInvoked为true,点击后会触发选中状态(蓝色竖线、背景变暗)。你之前尝试的模板、样式修改无效,是因为这些操作未触及WinUI原生控件的这个核心属性,必须通过自定义渲染器直接修改底层控件配置才能生效。
内容的提问来源于stack exchange,提问作者dalchri
相关产品推荐
相关产品推荐

