UWP应用中修改ComboBox选中项背景色的方法求助
修改UWP ComboBox下拉选中项背景色(无需Trigger)
你需要修改的是ComboBoxItem的默认样式,因为下拉列表里的每一项都是ComboBoxItem控件,它的选中状态背景是在自身样式的VisualState里定义的,不用Trigger就能搞定,步骤如下:
在Visual Studio里打开你的XAML文件,右键选中目标ComboBox,选择「编辑模板」→「编辑副本」,选择要存放样式的位置(比如当前窗口的Resources),确认后会自动生成完整的ComboBox样式和关联的ComboBoxItem样式。
在生成的资源里找到名为
ComboBoxItemStyle1(默认命名,可自行修改)的Style,找到里面的<VisualStateGroup x:Name="SelectionStates">节点,下面有几个和选中相关的VisualState:Selected:选中且获得焦点时的状态SelectedUnfocused:选中但失去焦点时的状态SelectedPressed:选中且被按下时的状态
修改这些VisualState里的
Background设置为你想要的颜色,比如红色:<VisualState x:Name="Selected"> <VisualState.Setters> <Setter Target="RootGrid.Background" Value="Red"/> <Setter Target="ContentPresenter.Foreground" Value="White"/> <!-- 可顺便改文字颜色,避免看不清 --> </VisualState.Setters> </VisualState> <VisualState x:Name="SelectedUnfocused"> <VisualState.Setters> <Setter Target="RootGrid.Background" Value="Red"/> <Setter Target="ContentPresenter.Foreground" Value="White"/> </VisualState.Setters> </VisualState> <VisualState x:Name="SelectedPressed"> <VisualState.Setters> <Setter Target="RootGrid.Background" Value="DarkRed"/> <!-- 按下时用稍深的红色,增强交互反馈 --> <Setter Target="ContentPresenter.Foreground" Value="White"/> </VisualState.Setters> </VisualState>确保你的ComboBox已经关联了这个修改后的ComboBoxItem样式,生成的ComboBox样式里默认会有一行
<Setter Property="ItemContainerStyle" Value="{StaticResource ComboBoxItemStyle1}"/>,如果没有,手动添加即可。
这样修改后,下拉列表里的选中项背景就会变成红色,完全不需要使用Trigger。
内容的提问来源于stack exchange,提问作者Hardik
相关产品推荐
相关产品推荐

