はじめに
先日のサンプルを改良し、特定の行の背景色を変更してみました。
StyleSelector を用意
public class ListViewStyleSelector : StyleSelector { public override Style SelectStyle(object item, DependencyObject container) { var slip = (Slip)item; if ((slip.No % 2) == 0) { var f = (FrameworkElement)container; return f.FindResource("alternateStyle") as Style; } else { return null; } } }
ほぼ、囚人さんのエントリの写経。
Slip.No を使って判断しているから、厳密な偶数行じゃない。
XAML を修正
<Window x:Class="ListViewSample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ListViewSample="clr-namespace:ListViewSample" Title="Window1" Height="400" Width="500"> <Window.Resources> <!--ListView 用の StyleSelector--> <ListViewSample:ListViewStyleSelector x:Key="listViewStyleSelector"/> </Window.Resources> <Grid> <!-- StyleSelector を指定--> <ListView x:Name="listView1" ItemsSource="{Binding}" ItemContainerStyleSelector="{StaticResource listViewStyleSelector}"> <ListView.Resources> <!--得意先列ヘッダ用テンプレート--> <DataTemplate x:Key="customerHeaderTemplate"> <StackPanel> <Label Content="得意先コード"/> <Label Content="得意先名"/> </StackPanel> </DataTemplate> <!--得意先セル用テンプレート--> <DataTemplate x:Key="customerCellTemplate"> <StackPanel> <Label Content="{Binding Path=CustomerCode}"/> <Label Content="{Binding Path=CustomerName}"/> </StackPanel> </DataTemplate> <!--伝票種列ヘッダ用テンプレート--> <DataTemplate x:Key="kindHeaderTemplate"> <StackPanel> <Label Content="伝票種"/> <Label Content="伝票番号フラグ"/> </StackPanel> </DataTemplate> <!--伝票種セル用テンプレート--> <DataTemplate x:Key="kindCellTemplate"> <StackPanel> <Label Content="{Binding Path=Kind}"/> <Label Content="{Binding Path=NoFlag}"/> </StackPanel> </DataTemplate> <!--偶数行に適用するスタイル--> <Style x:Key="alternateStyle" TargetType="{x:Type ListViewItem}"> <Setter Property="Background" Value="Gold"/> </Style> </ListView.Resources> <ListView.View> <GridView> <!--列を追加。--> <!--DisplayMemberBinding を使って、列に表示する Slip クラスのプロパティを指定しています--> <GridViewColumn Header="伝票日付" DisplayMemberBinding="{Binding Path=Date}"/> <!--伝票種列ヘッダ用のテンプレートと伝票種セル用のテンプレートを指定--> <GridViewColumn HeaderTemplate="{StaticResource kindHeaderTemplate}" CellTemplate="{StaticResource kindCellTemplate}"/> <GridViewColumn Header="伝票番号" DisplayMemberBinding="{Binding Path=No}"/> <!--得意先列ヘッダ用のテンプレートと得意先セル用のテンプレートを指定--> <GridViewColumn HeaderTemplate="{StaticResource customerHeaderTemplate}" CellTemplate="{StaticResource customerCellTemplate}"/> </GridView> </ListView.View> </ListView> </Grid> </Window>