How to: Get a ComboBoxItem

If you need to get a specific ComboBoxItem at a particular index in a ComboBox you can use ItemContainerGenerator. The following example shows the ComboBox and its items.


<ComboBox Name="cb" Margin="10,10,3,3" Width="200" Height="30" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" VerticalAlignment="Top" 
             IsEditable="true" Text="Open Combo Box" IsReadOnly="true" 
             StaysOpenOnEdit="true" IsDropDownOpen="true">
        <ComboBoxItem>Spain - Item 0</ComboBoxItem>
        <ComboBoxItem>France - Item 1</ComboBoxItem>
        <ComboBoxItem>Peru - Item 2</ComboBoxItem>
        <ComboBoxItem>Mexico - Item 3</ComboBoxItem>

This example shows how to retrieve the item by specifying the index of the item in the ContainerFromIndex property.

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

    Dim cbi As ComboBoxItem = CType( _
            cb.ItemContainerGenerator.ContainerFromIndex(0), ComboBoxItem)

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

Once you have retrieved the ComboBoxItem you can do things such as display the contents of the item as shown in this example.

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

For the complete sample see Get ComboBoxItem with Index Sample.

See Also

Community Additions