.NET MAUI中如何通过AppShell修改Tab Bar及图标颜色
.NET MAUI 修改TabBar及图标颜色的两种实用方法
方法一:直接通过Shell内置属性快速设置
你可以直接在Shell或TabBar标签上添加Shell专属属性,快速修改TabBar的背景色、选中/未选中状态的图标和文字颜色:
修改后的AppShell.xaml代码示例:
<?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="ECommerceApp.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ECommerceApp" xmlns:pages="clr-namespace:ECommerceApp.Pages" Shell.FlyoutBehavior="Disabled" Shell.TabBarBackgroundColor="#2C3E50" <!-- TabBar背景色 --> Shell.TabBarSelectedColor="#3498DB" <!-- 选中状态的图标/文字颜色 --> Shell.TabBarUnselectedColor="#BDC3C7"> <!-- 未选中状态的图标/文字颜色 --> <TabBar> <Tab Title="Home" Icon="home"> <ShellContent ContentTemplate="{DataTemplate pages:HomePage}" /> </Tab> <Tab Title="Cart" Icon="cart"> <ShellContent ContentTemplate="{DataTemplate pages:CartPage}" /> </Tab> <Tab Title="Favorites" Icon="faqvorite"> <ShellContent ContentTemplate="{DataTemplate pages:FavoritesPage}" /> </Tab> <Tab Title="Settings" Icon="settings"> <ShellContent ContentTemplate="{DataTemplate pages:SettingsPage}" /> </Tab> </TabBar> </Shell>
- 这些属性加在
Shell标签上时,全局所有TabBar都会生效;如果只想给当前TabBar设置,把属性移到<TabBar>标签内即可。
方法二:自定义Style(适合复杂定制)
如果需要更灵活的控制(比如区分平台样式、复用样式),可以在Shell的资源中定义自定义Style:
<?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="ECommerceApp.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:ECommerceApp" xmlns:pages="clr-namespace:ECommerceApp.Pages" Shell.FlyoutBehavior="Disabled"> <Shell.Resources> <Style x:Key="CustomTabBarStyle" TargetType="TabBar"> <Setter Property="Shell.TabBarBackgroundColor" Value="#2C3E50" /> <Setter Property="Shell.TabBarSelectedColor" Value="#3498DB" /> <Setter Property="Shell.TabBarUnselectedColor" Value="#BDC3C7" /> <!-- 可选:单独控制文字颜色 --> <Setter Property="Shell.TabBarTitleColor" Value="#3498DB" /> <Setter Property="Shell.TabBarUnselectedTitleColor" Value="#BDC3C7" /> </Style> </Shell.Resources> <TabBar Style="{StaticResource CustomTabBarStyle}"> <!-- 你的Tab内容不变 --> </TabBar> </Shell>
位图图标额外处理
如果你的图标是PNG等位图(而非矢量SVG),Shell的颜色属性无法直接覆盖图标颜色,需要准备选中/未选中两种状态的图标,然后通过Tab的Icon和SelectedIcon属性设置:
<Tab Title="Home" Icon="home_unselected" SelectedIcon="home_selected"> <ShellContent ContentTemplate="{DataTemplate pages:HomePage}" /> </Tab>
内容的提问来源于stack exchange,提问作者Rowan
相关产品推荐
相关产品推荐

