1. 程式人生 > >WPF:改變ListBoxItem和ListViewItem的顏色

WPF:改變ListBoxItem和ListViewItem的顏色

自定義 erb sta 討論 class sem borde spa 方法

目錄

  • 1. 改變ListBoxItem顏色
  • 2. ListViewItem的顏色設置

註意:

本文僅討論默認ListBoxItem和ListViewItem的鼠標指向和被選擇後的前景和背景顏色設置。如果你想要更高的需求,建議寫更詳細的空間模板和數據模板。

返回目錄

1. 改變ListBoxItem顏色

有很多改變ListBoxItem顏色的方案,比如這篇文章:自定義WPF ListBox的選擇樣式。不過我認為下面這種方法比較好:

過程是首先通過觸發器(Trigger)先判斷ListBoxItem是否被選定(通過IsSelected屬性)和是否被鼠標指向(通過IsMouseOver屬性)來設置ListBoxItem的Background和Foreground。但是直接這樣完成的話鼠標顏色是可以改變,而選擇顏色仍然不會改變。原因是系統默認主題針對ListBoxItem的控件模板在被選擇後沒有使用ListBoxItem的Background屬性做背景顏色。所以此時需要手動更改ListBoxItem的控件模板讓其直接使用ListBoxItem的Background屬性。

技術分享

(如圖:鼠標指向ListBoxItem的顏色和選擇的顏色都正確被顯示)

XAML:

<ListBox>

<!-- 數據 -->

<ListBoxItem>AAAA</ListBoxItem>

<ListBoxItem>BB</ListBoxItem>

<ListBoxItem>CCCC</ListBoxItem>

<!-- 設置ListBoxItem樣式 -->

<ListBox.ItemContainerStyle>

<Style TargetType="ListBoxItem">

<!-- 設置控件模板 -->

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="ListBoxItem">

<Border Background="{TemplateBinding Background}">

<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"

VerticalAlignment="{TemplateBinding VerticalContentAlignment}"

TextBlock.Foreground="{TemplateBinding Foreground}"/>

</Border>

</ControlTemplate>

</Setter.Value>

</Setter>

<!-- 設置觸發器 -->

<Style.Triggers>

<Trigger Property="IsSelected" Value="true">

<Setter Property="Background" Value="Black"/>

<Setter Property="Foreground" Value="White"/>

</Trigger>

<Trigger Property="IsMouseOver" Value="true">

<Setter Property="Background" Value="LightGreen"/>

<Setter Property="Foreground" Value="Red"/>

</Trigger>

</Style.Triggers>

</Style>

</ListBox.ItemContainerStyle>

</ListBox>

返回目錄

2. ListViewItem的顏色設置

令人高興的是,上述ListBoxItem觸發器不能解決的問題在ListViewItem上並沒有問題,因此直接用樣式的觸發器就可以設置好ListViewItem的顏色。

技術分享

XAML:

<Window.Resources>

<!-- 數據 -->

<x:ArrayExtension x:Key="arr"

xmlns="clr-namespace:System;assembly=mscorlib"

Type="String">

<String>hehe long long long long long long long</String>

<String>12345678900-78976587865</String>

</x:ArrayExtension>

</Window.Resources>

<ListView ItemsSource="{StaticResource arr}">

<!-- 列 -->

<ListView.View>

<GridView>

<GridViewColumn Header="文字"

DisplayMemberBinding="{Binding}"/>

<GridViewColumn Header="長度"

DisplayMemberBinding="{Binding Length}"/>

</GridView>

</ListView.View>

<ListView.ItemContainerStyle>

<Style TargetType="{x:Type ListViewItem}">

<!-- 設置觸發器 -->

<Style.Triggers>

<Trigger Property="IsSelected" Value="true">

<Setter Property="Background" Value="Black"/>

<Setter Property="Foreground" Value="White"/>

</Trigger>

<Trigger Property="IsMouseOver" Value="true">

<Setter Property="Background" Value="LightGreen"/>

<Setter Property="Foreground" Value="Red"/>

</Trigger>

</Style.Triggers>

</Style>

</ListView.ItemContainerStyle>

</ListView>

WPF:改變ListBoxItem和ListViewItem的顏色