如何更改MAUI Flyout菜单中选中项的颜色?
问题:如何修改MAUI Shell中FlyoutItem选中时的样式
我有如下代码块用于设置FlyoutItem的样式:
<Style TargetType="FlyoutItem" x:Key="HomeFlyout"> <Setter Property="FlyoutIcon" Value="home_icon.png" /> <Style.Triggers> <Trigger TargetType="FlyoutItem" Property="IsChecked" Value="False"> </Trigger> <Trigger TargetType="FlyoutItem" Property="IsChecked" Value="False"> <!-- Code to triger background change --> </Trigger> </Style.Triggers> </Style>
该样式在FlyoutItem中的使用方式如下:
<Application.MainPage> <Shell> <FlyoutItem Title="Home" Style="{StaticResource HomeFlyout}"> <ShellContent Title="Home" ContentTemplate="{DataTemplate page:HomePage}" FlyoutItemIsVisible="True" /> </FlyoutItem> </Shell> </Application.MainPage>
我希望选中项(例如Home标签)能改变样式,已尝试设置Setter Property="BackgroundColor" Value="LightBlue"及BackgroundColor="{Binding BackgroundColor}",但未成功,请问该如何实现?
解决方案
MAUI Shell的FlyoutItem默认模板里,BackgroundColor并非直接作用于选中区域,需要通过修改控件模板或视觉状态来实现样式变更,以下是两种可行方案:
方案1:自定义控件模板+视觉状态
修改原有样式,通过自定义ControlTemplate覆盖默认布局,并为选中状态设置样式:
<Style TargetType="FlyoutItem" x:Key="HomeFlyout"> <Setter Property="FlyoutIcon" Value="home_icon.png" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Grid BackgroundColor="{TemplateBinding BackgroundColor}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="Selected"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="LightBlue" /> <!-- 可额外设置文字颜色等样式 --> <Setter TargetName="TitleLabel" Property="TextColor" Value="White" /> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <!-- 还原FlyoutItem默认布局结构 --> <StackPanel Orientation="Horizontal" Padding="16,12"> <Image Source="{TemplateBinding FlyoutIcon}" WidthRequest="24" HeightRequest="24" Margin="0,0,12,0" /> <Label x:Name="TitleLabel" Text="{TemplateBinding Title}" VerticalOptions="Center" /> </StackPanel> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
方案2:全局触发器样式
如果希望所有FlyoutItem统一应用选中样式,可在Shell资源中设置全局样式,无需单独指定每个FlyoutItem的样式:
<Shell.Resources> <Style TargetType="FlyoutItem"> <Setter Property="BackgroundColor" Value="Transparent" /> <Style.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="BackgroundColor" Value="LightBlue" /> </Trigger> </Style.Triggers> </Style> </Shell.Resources>
注:该全局样式生效的前提是,单个FlyoutItem未设置局部样式覆盖全局规则。
关键说明
- 直接设置
BackgroundColor无效,是因为FlyoutItem的默认模板中,背景由内部容器控制,必须通过控件模板或视觉状态穿透修改。 - 若使用绑定方式,需确保ViewModel中的
BackgroundColor属性实现INotifyPropertyChanged接口,并在选中状态变化时更新属性值。
内容的提问来源于stack exchange,提问作者Adam Gong
相关产品推荐
相关产品推荐

