ListBoxで選択された項目の背景の色などを変更してみる。
コントロールの状態によって見た目を変える場合はTriggerを使う。
IsSelectedプロパティがTrueの時だけ、ListBoxItemのBackgroundプロパティやForegroundプロパティを変更する。
ListBoxItemのスタイル設定は、ItemContainerStyleプロパティから行う事が出来る。
但し、これだけでは背景色の変更がうまくいかないようなので、ListBoxItemのTemplateも設定している。
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="250">
<Grid Margin="20">
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="{TemplateBinding Background}">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="ForestGreen"/>
<Setter Property="Foreground" Value="Gold"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBoxItem>test1</ListBoxItem>
<ListBoxItem>test2</ListBoxItem>
<ListBoxItem>test3</ListBoxItem>
<ListBoxItem>test4</ListBoxItem>
<ListBoxItem>test5</ListBoxItem>
</ListBox>
</Grid>
</Window>
ListBoxItemのスタイルを設定 (11~29行目)
ItemContainerStyleプロパティからスタイルを設定する。
StyleのTargetTypeは”ListBoxItem”となる。(ComboBoxの時はComboBoxItem)
ListBoxItemのTemplateを設定 (13~21行目)
TemplateでListBoxItemの中身をBorderに書き換える。
BorderのBackgroundプロパティはTemplateBindingを使って元のBackgroundをセットしている。
Borderの中にContentPresenterを入れる事で項目毎のコンテンツを表示する事が出来る。
色を変える (22~27行目)
Triggerを使ってIsSelectedプロパティがTrueの時だけBackgroundとForegroundを変更している。


コメント
コメントを投稿