リストボックス
最終更新:
atachi
リストボックスはListBoxクラスによって実装されたデータ駆動型コントロールです。
表示するデータはWPFから設定するか、ListBox.ItemsSourceプロパティへコレクションをバインドして設定します。
使い方
SelectionMode属性 を設定し、複数のアイテムを選択可能にしています。
ListBoxItem には IsSelected属性 で選択状態を設定します。SelectionMode属性がTrueにセットされていない場合に、ListBoxItem.IsSelectedが複数設定されていても1つしか選択された状態にはならないので注意が必要です。
<ListBox Name="listBox1" SelectionMode="Multiple">
<ListBoxItem>北海道</ListBoxItem>
<ListBoxItem>青森</ListBoxItem>
<ListBoxItem>秋田</ListBoxItem>
<ListBoxItem IsSelected="True">岩手</ListBoxItem>
<ListBoxItem IsSelected="True">山形</ListBoxItem>
<ListBoxItem>宮城</ListBoxItem>
</ListBox>
アイテムの描画
ListBoxItem要素 内に任意のコントロールを描画します。
<ListBox Grid.Row="2" Name="listBox1">
<ListBoxItem>
<Rectangle Fill="AntiqueWhite" Width="100" Height="25"/>
</ListBoxItem>
<ListBoxItem>
<Grid>
<Rectangle Fill="Coral" />
<TextBlock Text="青森" />
</Grid>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<TextBox Width="30" Text="1" />
<TextBox Width="30" Text="2" />
<TextBox Width="30" Text="3" />
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<Button Content="実行" />
</ListBoxItem>
<ListBoxItem IsSelected="True">山形</ListBoxItem>
<ListBoxItem>宮城</ListBoxItem>
</ListBox>
Tips
スムーズなスクロール
ListBoxでは項目のスクロールは、「項目単位」でスクロールするようになっています。
これをスムーズなスクロール(ドット単位でのスクロール)に変更することができます。
<ListBox ScrollViewer.CanContentScroll="False" />
CanContentScrollプロパティの値をFalseに設定すると、スムーズなスクロールになります。
アイテムを横幅全体に表示する
通常の使用方法では気にする必要はありませんが、項目をDataTemplateを使って表示するに項目がListBoxの幅全体を使って表示してほしい場合があります。
ListBox.HorizontalContentAlignmentプロパティを明示的にStretchと指定することで各要素の横幅が全体に表示されます。
↓設定後
項目の横にあるスペースをなくす
ListBoxの要素に使用されているListBoxItemクラスのスタイルで定義されているPaddingプロパティが原因です。
次のようにItemContainerStyleを使ってListBoxItemに設定するスタイルを設定することで、スペースが無くなります。
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="0"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
表示データをバインディングで指定
string型のコレクションをバインドします。
ObservableCollection<string> items = new ObservableCollection<string>();
items.Add("北海道");
items.Add("青森");
items.Add("秋田");
items.Add("山形");
<ListBox ItemsSource="{Binding items}" />
ItemsSourceプロパティでバインドされたコレクションは、1つずつListBoxで表示するための要素に変換されていきます。
デフォルトの設定では、各要素のToString()を呼び出して得られた文字列をListBoxに表示します。
上記のコードは、コレクションの要素がstring型なので、文字列がそのまま表示されていますが、プログラマが用意した独自型の場合には、ListBoxに表示したい文字列をToString()で返すか、次項で説明するデータテンプレートを使用します。
データテンプレート
データテンプレートを使うとListBoxのデータソースとバインドを使用して項目を表示できます。
ObservableCollection<Person> items = new ObservableCollection<Person>();
items.Add(new Person("佐藤 清"));
items.Add(new Person("山田 太郎"));
items.Add(new Person("小泉 武信"));
items.Add(new Person("加藤 健一郎"));
// Personクラスは次のような実装とする
public class Person {
public Person(string name){
FullName = name;
}
public string FullName{
get;
set;
}
}
<ListBox ItemsSource="{Binding items}" >
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="{Binding FullName}" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>