HOW TO:取得 ListBoxItem
如果您需要取得位於 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>
下列範例示範如何在 ItemContainerGenerator 的 ContainerFromIndex 屬性中指定項目的索引,以便擷取該項目。
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()) + ".";