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