天天看點

改變ListBoxItem選中的顔色

原文: 改變ListBoxItem選中的顔色

改變ListBoxItem主要是改變的style

下面直接看代碼吧!!!

1   <Style TargetType="{x:Type ListBoxItem}">
 2              <Setter Property="SnapsToDevicePixels" Value="true"/>
 3              <Setter Property="OverridesDefaultStyle" Value="true"/>
 4              <Setter Property="Template">
 5                  <Setter.Value>
 6                      <ControlTemplate TargetType="{x:Type ListBoxItem}">
 7  
 8                          <Grid SnapsToDevicePixels="true">
 9                              <Border x:Name="Border" Background="Aqua"/>
10                              <ContentPresenter />
11                          </Grid>
12                          <ControlTemplate.Triggers>
13                              <Trigger Property="IsSelected" Value="true">
14                                  <Setter Property="Background" TargetName="Border" Value="Red"/>
15                              </Trigger>
16                          </ControlTemplate.Triggers>
17                      </ControlTemplate>
18                  </Setter.Value>
19              </Setter>
20          </Style>      

在第一行代碼要注意的是

<Style TargetType="{x:Type ListBoxItem}">這裡沒有使用x:key屬性

這樣子產品下所有的ListBoxItem

總結:當ListBoxItem中指定了style時,就不會使用到以上定義的樣式。

根據上文指定了ListBoxItem 自動填充ListBox      
<ListBox.ItemContainerStyle>
3     <Style TargetType="ListBoxItem">
4       <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
5     </Style>
6   </ListBox.ItemContainerStyle>      
可以把上面的樣式寫在這裡,但是這兩個樣式不能同使用。      

繼續閱讀