如何:获取 ListBoxItem

更新:2007 年 11 月

如果需要获取 ListBox 中特定索引位置的特定 ListBoxItem,可以使用 ItemContainerGenerator

示例

下面的示例演示 ListBox 和它的项。

<ListBox Margin="10,0,0,5" Name="lb" VerticalAlignment="Top" Grid.Column="0" Grid.Row="2">
    <ListBoxItem>Item 0</ListBoxItem>
    <ListBoxItem>Item 1</ListBoxItem>
    <ListBoxItem>Item 2</ListBoxItem>
    <ListBoxItem>Item 3</ListBoxItem>
</ListBox>

下面的示例演示如何通过在 ItemContainerGeneratorContainerFromIndex 属性中指定项索引来检索项。

Private Sub GetIndex0(ByVal Sender As Object, ByVal e As RoutedEventArgs)

    Dim lbi As ListBoxItem = CType( _
        lb.ItemContainerGenerator.ContainerFromIndex(0), ListBoxItem)
    Item.Content = "The contents of the item at index 0 are: " + _
        (lbi.Content.ToString()) + "."
End Sub
private void GetIndex0(object sender, RoutedEventArgs e)
{
  ListBoxItem lbi = (ListBoxItem)
      (lb.ItemContainerGenerator.ContainerFromIndex(0));
  Item.Content = "The contents of the item at index 0 are: " +
      (lbi.Content.ToString()) + ".";
}

在检索过列表框项后,可以显示该项的内容,如下面的示例所示。

Item.Content = "The contents of the item at index 0 are: " + _
    (lbi.Content.ToString()) + "."
Item.Content = "The contents of the item at index 0 are: " +
    (lbi.Content.ToString()) + ".";