【WPF】ListBoxの選択状態のStyleをカスタマイズする。 #参考サイト ・ItemsControl攻略 ~外観のカスタマイズ http://grabacr.net/archives/1240 ・SystemColorsクラス http://msdn.microsoft.com/ja-jp/library/system.windows.systemcolors%28v=vs.110%29.aspx ・How do I change the selected item 'text' foreground color in a listbox http://stackoverflow.com/questions/14803225/how-do-i-change-the-selected-item-text-foreground-color-in-a-listbox
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
this.Text.Items.Add("hogehoge");
this.Text.Items.Add("hugehuge");
this.Text.Items.Add("aikazuyendo");
}
}
}
<Window x:Class="ListBoxTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<!-- ListBoxのItemPanelTemplate(Z字に項目を並べる) -->
<ItemsPanelTemplate x:Key="ListBoxItemsPanelTemplate">
<WrapPanel/>
</ItemsPanelTemplate>
<!-- ListBoxのDataTemplate(項目をLabelにする) -->
<DataTemplate x:Key="ListBoxItemTemplate">
<!-- 文字色をListBoxItemの色にする。 -->
<Label Content="{Binding}" Foreground="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=Foreground}"/>
</DataTemplate>
<!-- ListBoxのItemContainerStyle(今回のキモ。項目の既定背景色を緑にし、選択した場合はシステムの配色にする) -->
<Style x:Key="ListBoxItemContainerStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<!-- 背景色をTemplateBindingにする。 -->
<Border BorderBrush="Black" BorderThickness="1" Background="{TemplateBinding Background}">
<StackPanel Orientation="Horizontal">
<!-- ここが実際のItemになる。-->
<ContentPresenter />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<!-- 既定の背景色 -->
<Setter Property="Background" Value="Green"/>
<!-- 選択した時の配色-->
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Background" Value="{x:Static SystemColors.HighlightBrush}" />
<Setter Property="Foreground" Value="{x:Static SystemColors.HighlightTextBrush}" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</Style.Resources>
</Style>
<Style x:Key="ListBoxStyle" TargetType="{x:Type ListBox}">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="SelectionMode" Value="Single"/>
<Setter Property="ItemsPanel" Value="{StaticResource ListBoxItemsPanelTemplate}"/>
<Setter Property="ItemTemplate" Value="{StaticResource ListBoxItemTemplate}"/>
<Setter Property="ItemContainerStyle" Value="{StaticResource ListBoxItemContainerStyle}"/>
</Style>
</Window.Resources>
<Grid>
<ListBox x:Name="Text" Style="{StaticResource ListBoxStyle}"/>
</Grid>
</Window>