如何获取 ListBoxItem

如果需要在ListBoxItem中获取特定索引的ListBox,可以使用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>

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

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()) + ".";
}
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

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

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()) + "."