如何:创建水平的 ListBox

更新:2007 年 11 月

本示例演示如何通过定义样式来创建水平的 ListBoxListBoxItem 控件以水平方式列出并通过用户定义的分隔符分隔。此样式将 ListBoxItemsPanel 属性设置为水平的 StackPanel。下面的示例演示 SeparatorListBox 的样式。

示例

<Grid.Resources>
  <Style TargetType="Separator">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type Separator}">
          <Border Width="2" Height="12" Margin="4" Background="Gray"/>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

  <Style TargetType="ListBox">
    <Setter Property="ItemsPanel">
      <Setter.Value>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal"
                      VerticalAlignment="Center"
                      HorizontalAlignment="Center"/>
        </ItemsPanelTemplate>
      </Setter.Value>
    </Setter>
  </Style>

</Grid.Resources>


...


<ListBox Name="lb" 
         Margin="10, 10, 3, 3" Height="50"
         Grid.Column="0" Grid.Row="2"
         Grid.RowSpan="2"
         SelectionChanged="PrintText">
  <ListBoxItem>Item 1</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 2</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 3</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 4</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 5</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 6</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 7</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 8</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 9</ListBoxItem>
  <Separator/>
  <ListBoxItem>Item 10</ListBoxItem>
</ListBox>

有关完整示例,请参见 水平 ListBox 示例

此外,您还可以通过创建新的 ControlTemplate 来创建水平的 ListBox。有关更多信息,请参见 ItemsPanel 中的示例。