Поделиться через


Практическое руководство. Получение элемента ListBoxItem

Обновлен: Ноябрь 2007

Если требуется получить некоторый элемент 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>

В следующем примере продемонстрировано, как извлечь элемент по индексу в свойстве ContainerFromIndex класса ItemContainerGenerator.

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