17

WPFでは、これら2つの概念とListbox混同して います。誰かが私にもっと説明してもらえますか?ItemTemplateItemsPanelTemplate

ありがとうジョン

4

2 に答える 2

24

これを例で説明してみましょう。

<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>

そして結果:

WPF ListBox テンプレートの例

ItemTemplate、リスト内の各項目のレイアウトを決定します。一方、ItemsPanel個々のアイテムを含むパネルです。上記の定義を考えると、ビジュアル ツリーは次のようになります。

<StackPanel>
  <Border>
    <TextBlock Text="Alpha"/>
  </Border>
  <Border>
    <TextBlock Text="Beta"/>
  </Border>
  ....
</StackPanel>
于 2009-09-11T08:14:59.820 に答える
12

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 など) に変更することもできます。

于 2009-09-11T08:08:53.860 に答える