概要
XAMLを書いていると単純な要素を複数並べたいと思う時があります。
TextBlockを10個並べるのに、TextBlockが10個並ぶのは、効率的ではないですよね。
HAMLとかJADEのように、XAMLのプリプロセッサが欲しくなるところですが、ItemsControlを使う事によってある程度解消することが可能です。
ItemsControlは、List系のコントロールの親クラスです。
Styleを用意する
ItemsControlを使うとしても記述量が多くなっては、逆効果ですのでStyleを使って、共通的な項目を纏めておきます。
CommonResourceDictionary.xaml
<Style x:Key="HorizontalItemsControl" TargetType="ItemsControl">
<Setter Property="Margin" Value="0" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled" />
<Setter Property="ItemsControl.ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsControl.ItemContainerStyle">
<Setter.Value>
<Style TargetType="ContentPresenter">
<Setter Property="Margin" Value="0" />
</Style>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="VerticalItemsControl" TargetType="ItemsControl">
<Setter Property="Margin" Value="0" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled" />
<Setter Property="ItemsControl.ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsControl.ItemContainerStyle">
<Setter.Value>
<Style TargetType="ContentPresenter">
<Setter Property="Margin" Value="0" />
</Style>
</Setter.Value>
</Setter>
</Style>
ItemsControlを記述する。
ItemsSourceの記述量が多いのがちょっと気になりますが、Xamlだけで繰り返し要素を簡単に記述することができました。
Test.xaml
<ItemsControl Style="{DynamicResource HorizontalItemsControl}">
<ItemsControl.ItemsSource>
<x:Array xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Type="sys:String">
<sys:String>1</sys:String>
<sys:String>2</sys:String>
<sys:String>3</sys:String>
<sys:String>4</sys:String>
<sys:String>5</sys:String>
<sys:String>6</sys:String>
<sys:String>7</sys:String>
<sys:String>8</sys:String>
<sys:String>9</sys:String>
<sys:String>10</sys:String>
<sys:String>11</sys:String>
<sys:String>12</sys:String>
</x:Array>
</ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>