WPFでは、これら2つの概念とListbox
混同して
います。誰かが私にもっと説明してもらえますか?ItemTemplate
ItemsPanelTemplate
ありがとうジョン
WPFでは、これら2つの概念とListbox
混同して
います。誰かが私にもっと説明してもらえますか?ItemTemplate
ItemsPanelTemplate
ありがとうジョン
これを例で説明してみましょう。
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="SteelBlue" Padding="5" BorderBrush="Black"
BorderThickness="1" Margin="0,2">
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="DarkKhaki"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
そして結果:
はItemTemplate
、リスト内の各項目のレイアウトを決定します。一方、ItemsPanel
個々のアイテムを含むパネルです。上記の定義を考えると、ビジュアル ツリーは次のようになります。
<StackPanel>
<Border>
<TextBlock Text="Alpha"/>
</Border>
<Border>
<TextBlock Text="Beta"/>
</Border>
....
</StackPanel>
ItemTemplate は、ListBox でアイテムをレンダリングするために使用される DataTemplate を指定するために使用されます。ItemPanelTemplate は、ListBox の子を配置するために使用されるパネルを指定するために使用されます。
たとえば、ListBox が ObservableCollection にバインドされている場合、DataTemplate を指定して、各 Person オブジェクトをレンダリングする方法を指定する必要があります。
<ListBox ItemsSource={Binding Persons}>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text={Binding FirstName}/>
<TextBlock Text={Binding LastName}/>
<TextBlock Text={Binding Age}/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ListBox はデフォルトで StackPanel を使用しているため、各項目が垂直に配置されます。この動作を変更したい場合は、ItemPanelTemplate プロパティを使用します。
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
StackPanel を他のパネル (WrapPanel など) に変更することもできます。