如何在XAML中设置UWP AppBarToggleButton的选中状态颜色?
嘿,这个问题我熟!你想把AppBarToggleButton选中时的样式改成品牌的绿色背景+白色前景,还希望能统一设置不用逐个修改,有两种实用的方法,我给你一步步讲清楚~
如果你的整个应用品牌色就是#FF008000(绿色),那直接修改系统的全局强调色是最省事的,所有依赖强调色的控件都会自动适配。
打开你的App.xaml,在<Application.Resources>里添加以下画笔:
<Application.Resources> <ResourceDictionary> <!-- 把全局强调色替换为你的绿色 --> <SolidColorBrush x:Key="SystemAccentColor" Color="#FF008000"/> <!-- 控件选中时的背景色 --> <SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="#FF008000"/> <!-- 选中时的文本/图标前景色 --> <SolidColorBrush x:Key="SystemControlHighlightAltBaseHighBrush" Color="White"/> </ResourceDictionary> </Application.Resources>
这样设置后,你的AppBarToggleButton选中时就会自动变成绿色背景+白色前景,而且所有其他用了系统强调色的控件(比如CheckBox、RadioButton)也会同步改成这个风格。如果这符合你的全应用设计,这绝对是最快的方案。
如果你只想修改AppBarToggleButton的样式,不想动其他控件,那自定义样式是更好的选择。你可以通过Visual Studio快速生成默认模板,再修改选中状态的样式:
步骤1:生成默认样式副本
- 在XAML编辑器里右键点击任意一个
AppBarToggleButton - 选择「编辑模板」→「编辑副本」
- 选择要把样式存到哪里(比如当前页面的资源,或者全局的
App.xaml),点击确定
VS会自动生成完整的AppBarToggleButton默认模板,你只需要找到Checked相关的视觉状态,修改颜色即可。
步骤2:修改选中状态的样式
在生成的样式里,找到<VisualStateGroup x:Name="ApplicationViewStates">下的<VisualState x:Name="Checked">,修改它的动画:
<VisualState x:Name="Checked"> <Storyboard> <!-- 修改选中时的背景色为绿色 --> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Root" Storyboard.TargetProperty="Background"> <DiscreteObjectKeyFrame KeyTime="0" Value="#FF008000"/> </ObjectAnimationUsingKeyFrames> <!-- 修改选中时的文本前景色为白色 --> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="White"/> </ObjectAnimationUsingKeyFrames> <!-- 修改选中时的图标前景色为白色 --> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Icon" Storyboard.TargetProperty="Foreground"> <DiscreteObjectKeyFrame KeyTime="0" Value="White"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState>
如果需要,你还可以修改CheckedPointerOver(选中时鼠标悬停)、CheckedPressed(选中时按下)这些状态的样式,让交互更完整。
步骤3:应用样式
生成的样式会有一个x:Key,比如CustomAppBarToggleButtonStyle,你只需要给所有AppBarToggleButton设置这个样式:
<CommandBar Background="{StaticResource MapButtonsBackgroundAcrylic}"> <AppBarToggleButton x:Name="tog_view_mode" Icon="View" Label="View Mode" Style="{StaticResource CustomAppBarToggleButtonStyle}"/> <AppBarSeparator Foreground="White"/> <AppBarToggleButton x:Name="tog_edit_mode" Icon="Edit" Label="Edit Mode" Style="{StaticResource CustomAppBarToggleButtonStyle}"/> </CommandBar>
如果想让所有AppBarToggleButton自动使用这个样式,删掉样式里的x:Key属性就行,这样整个应用的AppBarToggleButton都会默认用这个自定义样式。
内容的提问来源于stack exchange,提问作者Graham

