ListBoxのItemContainerStyleプロパティを利用すると、生成された個々の要素に対してスタイルを適用させることができます。
下記コードでは、要素をマウスオーバーすると青色に、選択すると赤色に変わるように指定しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<Window.Resources> <Style x:Key="myStyle1" TargetType="{x:Type ListBoxItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border Background="{TemplateBinding Background}"> <ContentPresenter /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="Blue" /> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="Red" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid Margin="20"> <ListBox Name="lbTodoList" ItemContainerStyle="{StaticResource myStyle1}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Title}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> |
3行目
x:Key属性にmyStyle1と名付けたスタイルを作成しています。そのスタイルをマークアップ拡張として、ListBoxのItemContainerStyle(40行目)に設定しています。
要素を選択した様子
関連ページ
ListBoxを利用する[DataTemplate][ItemTemplate]