欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF中修改ListBox项的样式病修改选中项的背景颜色

程序员文章站 2022-06-25 17:03:10
最终效果: ......

最终效果:

  WPF中修改ListBox项的样式病修改选中项的背景颜色

 1         <ListBox Name="cmb">
 2             <!--修改颜色-->
 3             <ListBox.Resources>
 4                 <!--高亮背景色-->
 5                 <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
 6                 <!--非高亮背景色-->
 7                 <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Red"/>
 8                 <!--高亮文本色-->
 9                 <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
10                 <!--非高亮文本色-->
11                 <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Green"/>
12                 <Style TargetType="ListBox">
13                     <!--重定义ListBox中项的样式-->
14                     <Setter Property="ItemTemplate">
15                         <Setter.Value>
16                             <DataTemplate>
17                                 <Grid Margin="0" Width="150">
18                                     <Border Margin="5" BorderBrush="SteelBlue" BorderThickness="1" CornerRadius="5" Background="{Binding Path=Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}">
19                                         <Grid Margin="5">
20                                             <Grid.RowDefinitions>
21                                                 <RowDefinition/>
22                                                 <RowDefinition/>
23                                             </Grid.RowDefinitions>
24                                             <TextBlock Text="{Binding ID}"/>
25                                             <TextBlock Grid.Row="1"  Text="{Binding Name}"/>
26                                         </Grid>
27                                     </Border>
28                                 </Grid>
29                             </DataTemplate>
30                         </Setter.Value>
31                     </Setter>
32                     <!--自定义选中项的颜色-->
33                     <Setter Property="ItemContainerStyle">
34                         <Setter.Value>
35                             <Style TargetType="ListBoxItem">
36                                 <Style.Triggers>
37                                     <Trigger Property="ListBoxItem.IsSelected" Value="True">
38                                         <Setter Property="ListBoxItem.Background" Value="Green"/>
39                                     </Trigger>
40                                 </Style.Triggers>
41                             </Style>
42                         </Setter.Value>
43                     </Setter>
44                 </Style>
45             </ListBox.Resources>
46         </ListBox>